Object.assign() 메서드는 출처 객체들의 모든 열거 가능한 자체 속성을 복사해 대상 객체에 붙여넣습니다. 그 후 대상 객체를 반환합니다.
정적메소드(static)
라고 부릅니다.{}
(객체)뒤에 .saaign()
을 붙여서 직접적으로{}.assign()
을 사용할 수 없습니다.const target = { a: 1, b: 2 };
const source = { b: 4, c: 5 };
const returnedTarget = Object.assign(target, source);
console.log(target);
// expected output: Object { a: 1, b: 4, c: 5 }
console.log(returnedTarget);
// expected output: Object { a: 1, b: 4, c: 5 }
console.log(target === returnedTarget);
// true
위에서
target
과returenedTarget
은 같은 객체입니다. 같은 객체(메모리 주소)를 가리키고 있습니다.
참고 : 참조형 - {}, [], function
const a = {k: 123};
const b = {k: 123};
console.log(a === b);
// false
const returnedTarget = Object.assign({}, target, source);
console.log(target);
// expected output: Object { a: 1, b: 4, c: 5 }
console.log(returnedTarget);
// expected output: Object { a: 1, b: 4, c: 5 }
console.log(target === returnedTarget);
// false
const returnedTarget = Object.assign({}, target);
객체의 속성 이름들을 배열로 만들어 반환합니다.
cosnt user = {
name: 'Heropy',
age: 85,
email: 'thesecon@gmail.com'
}
cosnt keys = Object.keys(user);
console.log(keys);
// ['name', age', 'email']
console.log(user['email']);
// thesecon@gmail.com
위의 key값들을 이용해서 map으로 값 추출하기
const values = keys.map(key => user[key]);
console.log(values);
// ['Heropy', 85, 'thesecon@gmail.com']
user.email
로 객체의 속성들을 접근할 수 있지만, user['email']
로도 접근할 수 있습니다.