해나아부지 개발일지

Object.create vs new #JavaScript 본문

Developers/OOP

Object.create vs new #JavaScript

__APPA 2020. 7. 31. 00:14

Object.create(), new(생성자 함수) 모두 객체의 속성들을 상속받은 새로운 객체를 만들어 주는 것처럼 보인다.

 

Object.create

객체의 정의는 함수로부터 시작된다. 우리가 잘 아는 'object' ( { } ) 도 예외는 아니다.

 

함수가 정의될 때, constructor와 prototype도 함께 생성되는데 이것은 함수 내부의 접근을 도와주는 속성이다.

 

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

개발자 콘솔에 Shape라는 class를 정의하고 prototype 속성을 보자!

constructor 에는 Shape 자신이 함수로 정의되어 있고 __proto__에는 'Object'에서 상속받은 여러가지 메서드(함수)들이 정의되어 있다.

 

const Rectangle.prototype = Object.create(Shape.prototype);

 

Rectangle에는 constructor가 존재하지 않기 때문에 

Rectangle.prototype.constructor = Rectangle;

Rectangle.prototype의 constructor 속성을 Rectangle 자신을 생성한 함수로 지정을 해줘야만 한다.

 

class는 객체이기 때문에 prototype을 이용하면 속성 값에 접근할 수 있다. 속성의 추가나 메서드 함수를 추가해 줄 수 있다. 

 

new(생성자 함수)

function Car(){
    this.wheel = 18;
};

Car.prototype.cc = 2000;

//Using Object.create()
var audi = new Car();
var bmw = Object.create(Car.prototype);

console.log(bmw.wheel); //undefined
console.log(bmw.cc); //2000

//Using New Keyword
console.log(audi.wheel); //18
console.log(audi.cc); //2000

 

위의 예제를 보면 두 함수 사이의 차이점을 발견할 수 있다.

 

Object.create로 만든 bmw는 Car class의 this.wheel을 상속받지 못하고 new 로 만든 audi는 this.wheel을 상속 받았다.

 

결언

constructor가 실행 되느냐 안되느냐 의 차이가 있는 것 같다!

'Developers > OOP' 카테고리의 다른 글

ES6 Class 와 Super  (0) 2020.08.01
객체 지향 프로그래밍(OOP: Object-Oriented-Programming)이란?  (0) 2020.07.30
Comments