자바스크립트의 상속

5970 단어 javascript
Java, C# 또는 C++와 같은 클래스 기반 언어와 비교할 때 JavaScript는 약간 다릅니다. JavaScript는 동적이며 클래스 구현을 제공하지 않습니다. 하지만 ES2015에 도입된 class 키워드가 있지만 구문상의 설탕일 뿐입니다. JavaScript는 프로토타입 기반으로 유지됩니다.

프로토타입 체인

When it comes to inheritance, JavaScript only has one construct: objects. Each object has a private property which holds a link to another object called its prototype. That object also has a prototype on its own, and that object also and the next one and so on, until an object is reached with NULL as its prototype. By definition, null has no prototype , so it is the final link in this prototype chain.

As we can see now the prototype chain, inheritance in JavaScript is achieved with a chain of prototypes. There are different approaches on creating prototype chains. They have evolved over time as the languages updates and new features and syntax are added. Nearly all objects in JavaScript are instances of Object which sits on the top of a prototype chain.

The prototypal inheritance model itself is more powerful than the classic model. For example, it is fairly simple to build a classic model on top of a prototypal model.

There are three common ways to create a prototype chain:

  • functional
  • constructor functions
  • class-syntax constructors

This article will cover the functional approach on creating prototype chains.

프로토타입 상속(함수형)

The functional approach to creating prototype chains is to use Object.create . Let's have a look at an example. For the example code, we will use the animal and dog taxonomy, where animal is a prototype of dog.

const animal = {
  eat: function() {
    console.log(this.name + ' eats');
  },
};

const dog = Object.create(animal, {
  bark: {
    value: function() {
      console.log(this.name + ' woofs');
    },
  },
});

const henry = Object.create(dog, {
  name: { value: 'Henry' },
});

henry.bark();
henry.eat();

The animal is a plain JavaScript object, created with the object literal syntax, and the prototype is Object.prototype, as for every plain JavaScript object. The Object.create function takes two arguments. First one is the desired prototype of the object being created, and the second one is the properties you want to add or the Properties Descriptor Object , it's optional.

So, when dog is instantiated, the first argument is the animal object. So animal is the prototype of dog. When henry is instantiated the first argument is dog passed to Object.create is dog. So the full prototype chain ist:

  • the prototype of henry is dog
  • the prototype of dog is animal
  • the prototype of animal is Object.prototype.

The Property Descriptor is a JavaScript object that describes the characteristics of the properties on another object, and contains keys that will become the key name on the object being created.

The values of these keys are called Property Descriptor objects. The method Object.getOwnPropertyDescriptor can be used to get a property descriptor on any object. To describe the value of a property, the descriptor can either use value or get and set to create a property getter/setter. The other properties are associated meta-data for the property. There is a writable property that determines whether the property can be reassigned, and a enumerable property, which determines whether the property will be enumerated in property iterator abstractions (like Object.keys). The configurable property sets whether the property descriptor itself can be altered. The default for all of these meta-data keys is false. Read more about property descriptors at MDN .

dog and henry의 경우 속성 설명자는 값만 설정하여 열거할 수 없고, 쓸 수 없고, 구성할 수 없는 속성을 추가합니다.

JavaScript 런타임은 henry.eat가 호출될 때 다음 단계를 수행합니다.
  • 헨리가 먹을 속성이 있는지 확인하십시오. (아니오)
  • 헨리의 프로토타입이 강아지인지 확인(NO)
  • 동물인 개의 프로토타입이 먹을 속성이 있는지 확인(YES)
  • 이것을 henry로 설정하여 eat 함수를 실행하여 this.name이 'Henry'가 되도록 합니다.

  • TL;DR

    • Inheritance in JavaScript is achieved with a chain of prototypes
    • There are three common ways to create a prototype chain (functional, constructor functions, class-syntax constructors)

    Thanks for reading and if you have any questions , use the comment function or send me a message .

    If you want to know more about Javascript , have a look at these Javascript Tutorials .

    참조(큰 감사)

    MDN , JSNAD

    좋은 웹페이지 즐겨찾기