Development/Javascript

[JS] Object.assign

Rosie, Lee 2021. 10. 8. 00:36

객체(object)의 명령어인 assign에 대해 정리합니다.

 

MDN 공식 문서 참고해주세요.

https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/Object/assign

 

Object.assign() - JavaScript | MDN

Object.assign() 메서드는 출처 객체들의 모든 열거 가능한 자체 속성을 복사해 대상 객체에 붙여넣습니다. 그 후 대상 객체를 반환합니다.

developer.mozilla.org

하나 이상의 출처 객체로부터 대상 객체로 복사할 때 사용합니다. 
var fruit = {
  name: 'Banana',
  color: 'Yellow'
}

var food = {
  name: 'Banana',
  taste: 'Sweet'
}

const target = Object.assign(fruit, food)

console.log(target);
// output -> {name: "Banana", color: "Yellow", taste: "Sweet"}
console.log(fruit);
// output -> {name: "Banana", color: "Yellow", taste: "Sweet"}
console.log(food);
// output -> {name: "Banana", taste: "Sweet"}

원본 객체(fruit) 데이터가 출처 객체(food)로부터 복사되어 변경됩니다.

 

원본 객체를 변경시키지 않고, 새로운 객체를 만들어서 사용하는 방법이 있습니다.

첫 번째 인수 자리가 대상 객체이기 때문에, 첫 번째 인수 자리에 빈 객체를 넣으면 됩니다.

var fruit = {
  name: "Banana",
  color: "Yellow"
};

var food = {
  name: "Banana",
  taste: "Sweet"
};

const target = Object.assign({}, fruit, food);

console.log(target);
// output -> {name: "Banana", color: "Yellow", taste: "Sweet"}
console.log(fruit);
// output -> {name: "Banana", color: "Yellow"}
console.log(food);
// output -> {name: "Banana", taste: "Sweet"}

 

반응형