상세 컨텐츠

본문 제목

객체의 전개 구문

Front-End/Javascript

by devloper-jun 2024. 9. 25. 18:21

본문

- 객체의 전개 구문은 순서가 중요함. 작동의 순서차이로 인해 전혀 다른 객체가 될 수 있다.

const obj = {a:1, b:2}
const obj1 = {c:3, d:4}
const newObj = {...obj, ...obj1} // {a:1, b:2, c:3, d:4}
const FirObj = {...obj, c: 10} // {a:1, b:2, c:10}
const BacObj = {c: 10, ...obj} // {c:10, a:1, b:2}

 FirObj와 BacObj의 결과값은 다른데, 전개 구문 이후에 값 할당이 있다면 할당한 값이 이전에 전개했던 구문 값을 덮어씌움. 반대의 경우는 전개 구문이 해당 값을 덮어씀. 전개 구문에 있는 값을 덮어쓸 것인지 값을 받아들일지에 따라 순서에 차이가 발생함.

  • 객체 전개 구문 트랜스파일
/* before transpile */
const obj = {a:1, b:2}
const obj1 = {c:3, d:4}
const newObj = {...obj, ...obj1}

/* after transpile */
function ownKeys(object, enumerableOnly) {
	var keys = Object.keys(object)
    if(Object.getOwnPropertySymbols) {
    	var symbols = Object.getOwnPropertySymbols(object)
        enumerableOnly && (symbols = symbols.filter(function (sym) {
        	return Object.getOwnPropertyDescriptor(object, sym).enumerable
        })), keys.push.apply(keys, symbols)
    }
    return keys
}

function _objectSpread(target) {
	for(var i = 1; i < arguments.length; i++) {
    	var source = null != arguments[i] ? arguments[i] : {}
        i % 2 ? ownKeys(Object(soruce), !0).forEach(function (key) {
        	_defineProperty(target, key, source[key])
        }) 
        : Object.getOwnPropertyDescriptors
        ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source),)
        : ownKeys(Object(source)).forEach(function (key) {
        	Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key),)
        })
    }
    return target
}

function _defineProperty(obj, key, value) {
	if(key in obj) {
    	Object.defineProperty(obj, key, {
        	value: value,
            enumerable: true,
            configurable: true,
            writable: true,
        })
    }else {
    	obj[key] = value
    }
    return obj
}

var obj = {a:1, b:2,}
var obj1 = {c:3, d:4,}
var newObj = _objectSpread(_objSpread({}, obj), obj1)

- 객체의 속성값, descriptor, symbol 등을 확인하는 것 때문에 트랜스파일 이후에는 코드가 길어지기 때문에 사용시 주의할 필요가 있다.

  • 객체 초기자 (object shorthand assignment)는 ES6(ECMA2015)에 도입된 기능으로 객체 선언 시 객체에 넣을 키와 값을 가지고 있는 변수가 있다면 해당하는 값을 간결하게 넣어주는 방식.
const a = 1
const b = 1
const obj = { a, b, }

 - a: a 의 형식이 아닌 선언된 변수로 축약해서 작성이 가능

  • 객체 초기자 트랜스파일
/* before transpile */
const a = 1
const b = 1
const obj = {a, b,}

/* after transpile */
var a = 1
var b = 1
var obj = {a:a, b:b,}

- 트랜스파일 이후에도 별도의 작업 없이 키와 값 할당 형식을 사용했기 때문에 객체 초기자를 사용할 경우 간편하게 객체를 선언 가능.

관련글 더보기