Skip to content

JavaScript — Inheritance, delegation patterns and Object linking

chchoing88 edited this page Oct 20, 2019 · 1 revision

JavaScript — Inheritance, delegation patterns and Object linking

What is Inheritance

대부분 클래스 기반의 객체 지향 언어의 상속은 하나의 객체가 모든 프로퍼티 와 다른 객체의 행동들을 얻는 것입니다. Javascript 는 비록 class 키워드가 ES2015에서 소개 되었지만 클래스 기반의 언어는 아닙니다. 그것은 구문 층입니다. Javascript는 여전히 prototype 체인으로 작동하고 있습니다.

Classical Inheritance vs Prototypal Inheritance

https://miro.medium.com/max/1520/1*UZKbYsRuM1OVW3__aZdPdw.png

Classical Inheritance (non-javascript)

  • Vehicle is 부모 클래스 입니다. 그리고 v1,v2Vehicle 의 인스턴스 입니다.
  • CarVehicle 의 자식 클래스 입니다. 그리고 c1, c2Car 의 인스턴스들 입니다.
  • 고전적인 상속에서는 클래스를 확장 할 때 부모 클래스와 자식 클래스가 별도의 엔티티 인 동작을 부모 클래스에서 자식으로 복사합니다.
  • 마찬가지로 클래스에서 인스턴스 또는 객체를 만들 때 두 가지 동작의 또 다른 복사본이 발생하며 둘 다 별도의 엔터티입니다.
  • car는 차량과 자동차 청사진으로 제조 된 것처럼 보이지만 그 이후에는 사본이기 때문에 연결되어 있지 않기 때문에 둘 다 별도의 개체입니다. 이것이 모든 화살표가 아래쪽으로 내려가는 이유입니다 (속성 및 동작이 아래로 흐릅니다).

Prototypal Inheritance (Behavior delegation pattern)

  • v1v2Vehicle.prototype 로 연결 되어있습니다. 왜냐하면 new keyword를 사용해서 생성 되었기 때문입니다.
  • 마찬가지로, c1c2Car.prototype 에 연결 되어 있습니다. 그리고 Car.prototypeVehicle.prototype 과 연결 되어있습니다.
  • JavaScript에서 객체를 만들 때 속성이나 동작을 복사하지 않고 링크를 만듭니다. 클래스가 확장되는 경우에도 비슷한 종류의 연결이 생성됩니다.
  • 모든 화살표는 행동 위임 링크이기 때문에 전통적인 비 JS 상속과 비교하여 반대 방향으로 이동합니다. 이러한 링크를 프로토 타입 체인이라고합니다.
  • 이 패턴을 JavaScript에서 _ prototypal inheritance _ 라고하는 Behavior Delegation Pattern 이라고합니다.

** prototype ** ** chain **에 대한 자세한 내용은 기사 [JavaScript-Prototype] (https://codeburst.io/javascript-prototype-cb29d82b8809)을 참조하십시오.

Example of prototypal inheritance

  • 클래식 상속을 달성하기 위해 Object.create () 사용.
  • 아래 코드는 스니펫 입니다., Car.prototypeVehicle.prototypeObject.create ()함수의 도움으로 연결됩니다.
// Vehicle - superclass
function Vehicle(name) {
  this.name = name;
}

// superclass method
Vehicle.prototype.start = function() {
  return "engine of "+this.name + " starting…";
};

// Car - subclass
function Car(name) {
  Vehicle.call(this,name); // call super constructor.
}

// subclass extends superclass
Car.prototype = Object.create(Vehicle.prototype);
// subclass method
Car.prototype.run = function() {
  console.log("Hello "+ this.start());
};

// instances of subclass
var c1 = new Car("Fiesta");
var c2 = new Car("Baleno");

// accessing the subclass method which internally access superclass method
c1.run();   // "Hello engine of Fiesta starting…"
c2.run();   // "Hello engine of Baleno starting…"
  • 위의 코드에서 c1 객체는 프로토 타입 체인 아래로 인해run () 메소드와 start () 메소드에 액세스 합니다. 아래 다이어그램에서 알 수 있듯이 객체 c1 에는 이러한 메소드가 없지만 위쪽으로 연결되는 링크가 있습니다.
  • 위의 코드에서 키워드 thisc1c2 인 각 메소드의 현재 실행 컨텍스트에 지나지 않습니다.

키워드 ** this **를 자세히 이해하려면 [JavaScript-이 키워드와 새 키워드에 대한 모든 것] (https://codeburst.io/all-about-this-and-new-keywords-in-javascript) 기사를 참조하십시오. -38039f71780c).

위 코드의 다이어그램 표현

https://miro.medium.com/max/987/1*OEMd8RbQYOc3aonG4MY0EQ.png

Objects linked to other objects

  • 이제 객체와 객체 연결에만 중점을 두어 이전 예제 상속 코드를 단순화합니다.
  • 따라서 우리는 .prototype, constructornew 키워드를 제거하려고 시도하며 객체에 대해서만 생각합니다.
  • 우리는 Object.create () 함수를 사용하여 객체 사이의 모든 연결을 만들 것입니다.

아래는 이전 예제의 간단한 코드입니다.

// base object with methods including initialization
var Vehicle = {
  init: function(name) {
    this.name = name;
  },
  start: function() {
    return "engine of "+this.name + " starting…";
  }
}

// delegation link created between sub object and base object
var Car = Object.create(Vehicle);

// sub object method
Car.run = function() {
  console.log("Hello "+ this.start());
};

// instance object with delegation link point to sub object
var c1 = Object.create(Car);
c1.init('Fiesta');

var c2 = Object.create(Car);
c2.init('Baleno');

c1.run();   // "Hello engine of Fiesta starting…"
c2.run();   // "Hello engine of Baleno starting…"

위 코드의 다이어그램 표현

https://miro.medium.com/max/588/1*4zepJJxri6PgfxQIpMFiAA.png

  • 이제 new, 모든 .prototype, constructor 함수 및 call 메소드의 복잡성을 제거하고 여전히 동일한 결과를 달성 한 방법을 볼 수 있습니다.
  • 중요한 것은 객체 c1 이 다른 객체에 연결된 다음 다른 객체에 다시 연결되는 것입니다.
  • 이것을 개체 위임 패턴이라고도합니다.

Summary

복잡성을 피하기 위해 코드에서 이들을 사용하기 전에 프로토 타입 상속 및 프로토 타입 체인을 이해하는 것이 중요합니다.

참고 : JS Book Series를 모른다.

Clone this wiki locally