[TIL] Object.create() 에 대하여

Ditto·2020년 10월 29일
0

클래스를 만드는 여러가지 방법 중에서 가장 편한 방법은 class 키워드를 사용하는 것이라고 느껴지지만 오늘 스프린트 과제는 ES6와 그 이전 버전에서의 클래스 구현을 요구하고 있었다.

클래스의 메소드와 프로퍼티를 만들고 인스턴스를 생성하고, 상속을 하는 방법을 고민하는 시간이었다.


Object.create(proto[, propertiesObject])

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


위는 MDN에 나와있는 설명이지만 나에게는 선뜻 이해되지 않는 단어의 나열이었다. 프로토 타입 체인에서 열거가능하지 않은 속성은 무엇이며 새로 만든 객체에 추가될 속성 설명자는 또 무엇일까. 이해하기 어려운 내용이었으나 스프린트를 진행하며 완벽하진 않지만 쓰는법은 대충 알게 되었다.

class 키워드를 사용하지 않고 클래스와 인스턴스를 만들어 상속하는 과정을 구현하고, class 키워드를 사용한 클래스와 인스턴스, 그리고 상속의 구현까지 진행했다.

// 클래스의 생성
function Character(){
 	this.name = 'none';
  	this.birth = '2020.10.29'
}
// 클래스의 prototype에 move method 추가
Character.prototype.move = function(){
	return `${this.name} move now`;
};
// 인스턴스 생성 함수
function Warrior(){
	Character.call(this);
	this.name = 'warrior';
  	this.weapon = 'sword';
}

function Wizard(){
	Character.call(this);
  	this.name = 'wizard';
  	this.weapon = 'wand';
}

// 체이닝을 통한 상속(Warrior)
Warrior.prototype = Object.create(Character.prototype);
Warrior.prototype.constructor = Warrior;

// 체이닝을 통한 상속(Wizard)
Wizard.prototype = Object.create(Character.prototype);
Wizard.prototype.constructor = Wizard;

const warriorA = new Warrior();
const wizardA = new Wizard();

console.log(warriorA);
// warrior {name: "warrior", birth: "2020.10.29", weapon: "sword"}
//	birth: "2020.10.29"
//	name: "warrior"
//	weapon: "sword"
//	__proto__: character

console.log(wizardA);
// Wizard {name: "wizard", birth: "2020.10.29", weapon: "wand"}
//	birth: "2020.10.29"
//	name: "wizard"
//	weapon: "wand"
//	__proto__: Character
profile
늘 성장하는 개발자이고 싶습니다

0개의 댓글