프로토타입 체인

dice0314·2023년 5월 12일
0

프로토타입 체인

객체 간 상속을 구현하는 메커니즘

  • 모든 JavaScript 객체는 프로토타입과 연결되어 있다.
  • 클래스를 생성하였을 때 상속 받은 클래스가 없다면 생성한 클래스는 암묵적으로 Object클래스를 상속받는다.
  • 객체에서 속성, 메서드에 접근할 때 속성, 메서드가 없다면 JavaScript는 프로토타입 체인을 따라 상위 프로토타입으로 이동하여 속성과 메서드를 찾는다. 발견할 때까지 찾으며 ,최상위 객체인 Object.prototype까지 이동하여 원하는 속성, 메서드를 찾지 못한다면 undefined를 반환한다.
  • 여러 객체 간에 상속 관계를 형성할 수 있다.
  • 객체의 프로토타입은 .__proto__.prototype을 통해 접근할 수 있다.
  • ES6부터 Object.getPrototypeOf() 메서드를 사용하여 프로토타입에 접근할 수도 있다.
  • 프로토타입 체인을 통해 상속된 객체는 상위 프로토타입의 속성과 메서드를 원하는대로 사용이 가능하다.
  • 상속을 통해 객체에 새로운 속성과 메서드를 추가하거나 기존의 속성과 메서드를 재정의할 수 있다.

ES5 프로토타입 체인

function Car(brand, model, color) {
  this.brand = brand;
  this.model = model;
  this.color = color;
  this.speed = 0;

  this.accelerate = function() {
    this.speed += 10;
  };

  this.brake = function() {
    this.speed -= 10;
  };
}

function Airplane(brand, model, color) {
  Car.call(this, brand, model, color); // 상위 객체 Car의 생성자 호출
}

Airplane.prototype = Object.create(Car.prototype);
  • 프로토타입 체인을 이용하여 상속을 구현
  • call이나 apply 메서드를 사용하여 상위 클래스 생성자 호출 가능

ES6 프로토타입 체인

class Car {
  constructor(brand, model, color) {
    this.brand = brand;
    this.model = model;
    this.color = color;
    this.speed = 0;
  }

  accelerate() {
    this.speed += 10;
  }

  brake() {
    this.speed -= 10;
  }
}

class Airplane extends Car { // Airplane에 Car크클래스를 상속
  constructor(brand, model, color) {
    super(brand, model, color) // 상위 클래스의 brand, model, color을 가져온다.
  }
}
  • extends 키워드를 사용하여 상속을 구현
  • super 키워드를 사용하여 상위 클래스의 생성자 호출 가능
profile
정리노트

0개의 댓글