프로토타입 상속

Park, Jinyong·2020년 6월 17일
0

Small, but Valuable.

목록 보기
18/19

pseudoclassical

const Shape = function() {
  this.x = 0;
  this.y = 0;
}
Shape.prototype.move = function(x, y) {
  this.x += x;
  this.y += y;
}

const Rectangle = function(width, height) {
  Shape.apply(this, arguments);
  this.width = width;
  this.height = height;
}

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

const rect = new Rectangle(50, 100);
rect.move(5, 5);
console.log(rect.x); // 5
console.log(rect.y); // 5

기존의 클래스 정의 방법에서는 프로토타입 체인을 이용하여 상속을 구현할 수 있다. Object.create는 첫 번째 인자로 넘겨진 객체를 프로토타입으로 하는 객체를 생성해서 반환한다. 이를 Rectangle의 프로토타입으로 설정한다. 그러면, Rectangle.prototpyeShape의 프로토타입을 참조하고 있으므로, Rectangle.prototype.constructorShape를 참조한다. 이러면 Rectangle를 생성하는 것이 아니라 Shape를 생성한다. 그러므로, Shape 생성자 함수를 참조하는 Rectangle.prototype.constructorRectangle 생성자 함수를 참조할 수 있도록 다시 수정해주어야 한다.

그리고 Rectangle 생성자 함수 내부의 thisShape에서는 this와 다르기 때문에 Shape.apply(this, arguments)를 이용하여 서로의 this를 연결해주어야 한다.

class - ES6

class Shape {
  constructor(x, y) {
    this.x = 0;
    this.y = 0;
  }
  move(x, y) {
    this.x += x;
    this.y += y;
  }
}

class Rectangle extends Shape {
  constructor(width, height) {
    super();
    this.width = width;
    this.height = height;
  }  
}

const rect = new Rectangle(50, 100);
rect.move(5, 5);
console.log(rect.x); // 5
console.log(rect.y); // 5

class 키워드를 사용하면 훨씬 간단하고 명료하게 클래스를 정의할 수 있다.

기존의 방법에서 상속을 하기 위해 프로토타입을 연결해주고 생성자를 다시 원래대로 되돌리는 복잡한 과정을 거쳤지만, extends 키워드를 사용해서 쉽게 상속을 할 수 있다.

또한, 생성자 함수 간의 this는 간단하게 super()를 호출함으로서 연결할 수 있다.

0개의 댓글