스프레드 문법

let o1 = { M: 1 };
let o2 = { ...o1, L: 3 };
console.log(o2.L);
console.log(o2);         //{ M: 1, L: 3 }

스프레드(…)를 활용하여 자료구조를 불변으로 만들 수 있다.
위와같이 스프레드란 객체 o1이 있고 여기에 값이 3인 프로퍼티 L을 추가해야 한다면,
같이 새로운 객체를 만들어서 o1 대신 사용할 수 있는 문법을 뜻함

 

 

 

 

Object.assign()

 

let o1 = { M: 1 };
let o2 = Object.assign(Object.assign({}, o1), { L: 3 });
console.log(o2.L);

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

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

const target = { a: 1, b: 2 };
const source = { c: 4, d: 5 };

const returnedTarget = Object.assign(target, source);

구문

Object.assign(target, ...sources)
Copy to Clipboard

매개변수

target

목표 객체. 출처 객체의 속성을 복사해 반영한 후 반환할 객체입니다.

sources

출처 객체. 목표 객체에 반영하고자 하는 속성들을 갖고 있는 객체들입니다.

반환 값

목표 객체.

Object.assign()은 속성을 단순히 복사하거나 새로 정의하는 것이 아니라, 할당(assign)하는 것입니다. 

 

객체 복제

const obj = { a: 1 };
const copy = Object.assign({}, obj);
console.log(copy); // { a: 1 }

Object.create()

Object.create() 메서드는 지정된 프로토타입 객체 및 속성(property)을 갖는 새 객체를 만듭니다.

구문

Object.create(proto[, propertiesObject])

매개변수

proto새로 만든 객체의 프로토타입이어야 할 객체.propertiesObject선택사항. 지정되고 undefined가 아니면, 자신의 속성(즉, 자체에 정의되어 그 프로토타입 체인에서 열거가능하지 않은 속성)이 열거가능한 객체는 해당 속성명으로 새로 만든 객체에 추가될 속성 설명자(descriptor)를 지정합니다. 이러한 속성은 Object.defineProperties()의 두 번째 인수에 해당합니다.

반환값

지정된 프로토타입 개체와 속성을 갖는 새로운 개체.

예외

proto 매개변수가 null 또는 객체가 아닌 경우 TypeError 예외가 발생(throw).

Object.create()를 사용한 고전적인 상속방법

아래는 고전적인 상속방법으로 사용된 Object.create() 사용 예입니다. 이는 단일 상속 용으로, JavaScript가 지원하는 전부입니다.

// Shape - 상위클래스
function Shape() {
  this.x = 0;
  this.y = 0;
}

// 상위클래스 메서드
Shape.prototype.move = function(x, y) {
  this.x += x;
  this.y += y;
  console.info('Shape moved.');
};

// Rectangle - 하위클래스
function Rectangle() {
  Shape.call(this); // super 생성자 호출.
}

// 하위클래스는 상위클래스를 확장
Rectangle.prototype = Object.create(Shape.prototype);
Rectangle.prototype.constructor = Rectangle;

var rect = new Rectangle();

console.log('Is rect an instance of Rectangle?', rect instanceof Rectangle); // true
console.log('Is rect an instance of Shape?', rect instanceof Shape); // true
rect.move(1, 1); // Outputs, 'Shape moved.'

 

 

여러 객체에서 상속하고 싶은 경우엔 mixin이 사용가능합니다.
function MyClass() {
  SuperClass.call(this);
  OtherSuperClass.call(this);
}

MyClass.prototype = Object.create(SuperClass.prototype); // 상속
mixin(MyClass.prototype, OtherSuperClass.prototype); // mixin

MyClass.prototype.myMethod = function() {
  // 기능 수행
};
Copy to Clipboard

mixin 함수는 상위(super)클래스 프로토타입에서 하위(sub)클래스 프로토타입으로 함수를 복사하고, mixin 함수는 사용자에 의해 공급될 필요가 있습니다. mixin 같은 함수의 예는 jQuery.extend()입니다.

'JavaScript' 카테고리의 다른 글

[js] 브라우저 렌더링  (0) 2022.06.07
[js] promise all  (0) 2022.06.07
[js] 동적 타이핑  (0) 2022.06.06
[js] 데이터 타입의 필요성  (0) 2022.06.06
[js] JavaScript에서 이중 느낌표  (0) 2022.06.06

+ Recent posts