>  기사  >  es5에서 상속을 구현하는 방법

es5에서 상속을 구현하는 방법

DDD
DDD원래의
2024-08-13 16:48:20604검색

이 글에서는 프로토타입 기반 상속, 생성자 상속, 기생 상속이라는 세 가지 주요 방법에 초점을 맞춰 ES5의 상속 접근 방식을 설명합니다. 이 기사에서는 ex

es5에서 상속을 구현하는 방법

ES5 상속 접근 방식

ES5에서 상속은 여러 접근 방식을 통해 달성할 수 있습니다.

프로토타입 기반 상속

이것이 가장 일반적인 접근 방식입니다. ES5에서. 여기에는 기본 클래스(부모)를 만든 다음 기본 클래스의 속성과 메서드를 상속하는 새 개체를 만들어 이를 "하위 클래스화"하는 작업이 포함됩니다. 이는 하위 클래스 객체의 __proto__ 속성을 ​​조작하여 수행됩니다.__proto__ property of the subclass objects.

<code class="javascript">const Animal = {
  eat() {
    console.log("Eating...");
  }
};

const Dog = {
  __proto__: Animal,
  bark() {
    console.log("Woof!");
  }
};

const myDog = Object.create(Dog);
myDog.eat(); // logs "Eating..."
myDog.bark(); // logs "Woof!"</code>

Constructor Inheritance

This approach involves creating a base class constructor function and then extending it by defining a new constructor function that takes the base class constructor as an argument and adds additional properties and methods.

<code class="javascript">function Animal() {
  this.eat = function() {
    console.log("Eating...");
  }
}

function Dog(name) {
  Animal.call(this);
  this.name = name;
  this.bark = function() {
    console.log("Woof!");
  }
}

const myDog = new Dog("Luna");
myDog.eat(); // logs "Eating..."
myDog.bark(); // logs "Woof!"</code>

Parasitic Inheritance

This approach involves creating a temporary object that inherits from the base class and then uses that object to create the desired subclass. It is similar to prototype-based inheritance, but instead of modifying the __proto__

<code class="javascript">const Animal = {
  eat() {
    console.log("Eating...");
  }
};

const Dog = (function() {
  function AnimalProxy() {}
  AnimalProxy.prototype = Animal;
  const proxy = new AnimalProxy();
  proxy.bark = function() {
    console.log("Woof!");
  }
  return proxy;
})();

const myDog = Object.create(Dog);
myDog.eat(); // logs "Eating..."
myDog.bark(); // logs "Woof!"</code>
생성자 상속🎜🎜이 접근 방식에는 기본 클래스 생성자 함수를 만든 다음 기본 클래스 생성자 함수를 정의하여 이를 확장하는 작업이 포함됩니다. 클래스 생성자를 인수로 사용하고 추가 속성과 메서드를 추가합니다.🎜rrreee🎜기생 상속🎜🎜이 접근 방식에는 기본 클래스에서 상속되는 임시 개체를 만든 다음 해당 개체를 사용하여 원하는 하위 클래스를 만드는 작업이 포함됩니다. 프로토타입 기반 상속과 유사하지만 __proto__ 속성을 ​​수정하는 대신 기본 클래스와 하위 클래스 사이의 브리지 역할을 하는 새 객체를 생성합니다.🎜rrreee

위 내용은 es5에서 상속을 구현하는 방법의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.