jsクラスの継承について

プロトタイプチェーンの継承

function Cat(){
    
    }
Cat.prototype = new Animal();
Cat.prototype.name = 'cat';

// Test Code
var cat = new Cat();
console.log(cat.name);
console.log(cat.eat('fish'));
console.log(cat.sleep());
console.log(cat instanceof Animal); //true
console.log(cat instanceof Cat); //true

はじめに: ここで、新しい空のオブジェクトが Animal を指し、Cat.prototype がこの空のオブジェクトを指していることがわかります. これは、プロトタイプ チェーンに基づく継承です.

機能: プロトタイプ チェーンに基づいて、親クラスのインスタンスであり、サブクラスのインスタンスでもあります。

短所: 多重継承を実装できない


継承を構築します。

call または apply メソッドを使用して、親クラスのコンストラクターをサブクラスにバインドし、サブクラスのインスタンスを強化します。これは、親クラスのインスタンス プロパティをサブクラスにコピーすることと同じです (プロトタイプは使用されません)。

function Cat(name){
    
    
	Animal.call(this);
	this.name = name || 'Tom';
}

// Test Code
var cat = new Cat();
console.log(cat.name);
console.log(cat.sleep());
console.log(cat instanceof Animal); // false
console.log(cat instanceof Cat); // true

特徴:多重継承が可能

短所: 親クラスのインスタンスのプロパティとメソッドのみを継承でき、プロトタイプのプロパティとメソッドは継承できません。


インスタンス継承とコピー継承

インスタンスの継承: 親クラスのインスタンスに新しい機能を追加し、それをサブクラスのインスタンスとして返します

継承のコピー: 親要素のプロパティとメソッドをコピーします

上記の 2 つの実用性は強くないため、ここでは例を挙げません。


構成の継承:

これは、構造継承とプロトタイプ チェーン継承の組み合わせに相当します。親クラスの構築を呼び出すことで、親クラスのプロパティを継承し、パラメーターを渡す利点を保持し、親クラスのインスタンスをサブクラスのプロトタイプとして使用して関数の再利用を実現します

function Cat(name){
    
    
	Animal.call(this);
	this.name = name || 'Tom';
}
Cat.prototype = new Animal();
Cat.prototype.constructor = Cat;

// Test Code
var cat = new Cat();
console.log(cat.name);
console.log(cat.sleep());
console.log(cat instanceof Animal); // true
console.log(cat instanceof Cat); // true

機能: インスタンスのプロパティ/メソッドとプロトタイプのプロパティ/メソッドを継承できます

欠点: 親クラスのコンストラクターが 2 回呼び出され、2 つのインスタンスが生成される

寄生成分の継承:

寄生メソッドにより、親クラスのインスタンス属性が切り捨てられるため、親クラスの構築が 2 回呼び出されたときに、インスタンス メソッド/属性が 2 回初期化されません。

function Cat(name){
    
    
	Animal.call(this);
	this.name = name || 'Tom';
}(function(){
    
    
	// 创建一个没有实例方法的类
	var Super = function(){
    
    };
	Super.prototype = Animal.prototype;
	//将实例作为子类的原型
	Cat.prototype = new Super();
})();

// Test Code
var cat = new Cat();
console.log(cat.name);
console.log(cat.sleep());
console.log(cat instanceof Animal); // true
console.log(cat instanceof Cat); //true

より推奨

おすすめ

転載: blog.csdn.net/Robergean/article/details/120163139