02_Part_Prototype Chain

Hanbin Lee·2021년 4월 11일
0

codestates

목록 보기
2/7

오늘은 OOP를 js언어에서 구현하는 방법에 대해 배웠다. 배운 내용을 바탕으로
두가지 질문에 답을해보는 시간을 가져보려 한다.

  • __proto__, constructor, prototype 이 각각 어떤 관계를 가지고 있는지 조사해봅니다.
  • ES6 class 키워드 및 super 키워드 이용 방법을 알아봅니다.

__proto__, constructor, prototype의 관계

__proto__와 constructor는 prototype속성 안에 들어있는 속성으로
먼저, 각 속성의 의미를 정리하면...

  • __proto__ 속성은 해당 객체의 프로토타입 객체의 프로토타입을 뜻한다.
  • constructor속성은 해당 객체의 생성자 함수인 프로토타입 객체를 뜻한다.
<예시>

Car라는 클래스를 만들고 TypeA라는 클래스를 하위 프로토타입 객체로 선언한다.

function Car() {} //Car 클래스 선언.
function TypeA() {} //TypeA 클래스 선언.
TypeA.prototype = Object.create(Car.prototype); // Car클래스 상속.
TypeA.prototype.constructor = TypeA; //생성자 함수 지정.

TypeA클래스에 객체 carA를 생성한다.

let carA = new TypeA();

carA의 __proto__속성은 프로토타입 객체인 TypeA클래스의 프로토타입과 동일하다.

carA.__proto__ === TypeA.prototype; //true

carA의 constructor는 생성자 함수인 TypeA클래스이다.

carA.prototype.constructor === TypeA; //true

Class

이전에는 클래스 함수를 선언 할 때, Object.create메소드와 constructor속성을 지정해서 만들어야 했지만 ES6버전부터는 Class메소드를 통해 간단하게 클래스를 선언 할 수있다.

class Car {}

프로토타입 객체를 상속시키기 위해서는 extends메소드를 사용하면 된다.

class TypeA extends Car {}

만일, 인자를 받는 클래스를 선언한다면, 이전 방식으로는 this를 사용해야 했지만 ES6버전부터는 super메소드를 활용하면 된다.

function Car(name) {
	this.name = name;
}
function TypeA(name) {
	Car.call(this, name); // or Car.apply(this, aguments);
}
TypeA.prototype = Object.create(Car.prototype);
TypeA.prototype.constructor = TypeA;
class Car {
  constructor(name) {
    this.name = name;
  }
}
class TypeA extends Car {
  constructor(name) {
    super(name);
  }
}

그런데, super메소드는 생략이 가능하기 때문에 생략해도 위와 동일한 기능을 한다.

class Car {
  constructor(name) {
    this.name = name;
  }
}
class TypeA extends Car {}
profile
안녕하세요 백엔드 개발자 이한빈 입니다 :)

0개의 댓글

관련 채용 정보