자바스크립트/개념

자바스크립트 Object.assign() 메서드란?

Jake Seo 2023. 1. 1. 23:11

Object.assign() 이란?

  • target 이 된 오브젝트에 source 오브젝트의 프로퍼티 내용을 덧씌우고 싶을 때 유용한 메서드이다.
  • 단, enumerable own properties 만 복사되므로 유의해야 한다.
  • 새로운 객체를 만드는 방식이 아닌, 기존의 객체를 수정하는 방식으로 불변 작업이 아니다.

예제 코드들

const defaultOptions = {
  title: "ABC",
  text: "default text",
};

const customOptions = {
  text: "custom text",
};

const finalOptions = Object.assign({}, defaultOptions, customOptions);
console.log(finalOptions); // {title: 'ABC', text: 'custom text'}
  • finalOptions 에는 defaultOptions 의 속성에 customOptions 가 덮어진 결과가 들어간다.
  • 오브젝트에서 프로퍼티 전체를 덮어씌우고 싶지 않고, 특정한 프로퍼티만 바꿔서 덮어씌우고 싶을 때 유용하다.

단, 열거 불가능한 속성은 복사하지 않는다.

const defaultOptions = {
  title: "ABC",
  text: "default text",
};

const customOptions = {
  text: "custom text",
};

Object.defineProperty(defaultOptions, "property1", {
  value: "not enumerable",
});

console.log(defaultOptions); // {title: 'ABC', text: 'default text', property1: 'not enumerable'}

const finalOptions2 = Object.assign({}, defaultOptions, customOptions);
console.log(finalOptions2); // {title: 'ABC', text: 'custom text'}

위의 예제에서 property1 은 복사되지 않은 것을 볼 수 있다.

반응형