ホームページ  >  記事  >  ES5で継承を実装する方法

ES5で継承を実装する方法

DDD
DDDオリジナル
2024-08-13 16:48:20604ブラウズ

この記事では、プロトタイプベースの継承、コンストラクターの継承、寄生継承の 3 つの主要な方法に焦点を当てて、ES5 での継承のアプローチについて説明します。この記事では、各アプローチの長所と短所について説明し、コード例を提供します

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__ プロパティを変更する代わりに、基本クラスとサブクラスの間のブリッジとして機能する新しいオブジェクトを作成します。

以上がES5で継承を実装する方法の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

声明:
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。