Es 6 class継承およびsuper特性の詳細
10270 ワード
一、クラスの継承
classは
extends
キーワードで継承されますclass a{
constructor(x, y) {
this.x = x;
this.y = y;
}
toString(){
return this.x+' '+this.y;
}
}
// a, z
class b extends a{
constructor(x, y, z) {
super(x, y);// this
this.z = z;
}
toString2(){
return super.toString()+' '+this.z
}
}
usper上記の例では、親クラスのインスタンスオブジェクトthisが作成されています.
二、super詳細
superキーワードは、関数(
super()
)として使用してもよいし、オブジェクト(super
)として使用してもよいsuper
は親のコンストラクション関数を表し、サブクラスのコンストラクション関数はsuper constructor(x, y, z) {
super(x, y);// this
this.z = z;
}
superは親aの構造関数を表すが、サブクラスbの例を返し、super内部のthisが指すbである
super()
はa.prototype.constructor.call(this)
に相当するsuper
を関数とする場合はサブクラスのコンストラクション関数のみで、カスタム関数ではclass a{
}
class b extends a{
m(){
super();//
}
}
super
をオブジェクトとし、静的メソッドでは親を指し、通常のメソッドでは親のプロトタイプを指す.次に、一般的な方法を示します.
class a{
aa(){
return 233 }
}
class b extends a{
constructor(){
super();
console.log(super.aa());
}
}
var c = new b; // 233
上記のコードでは、サブクラスbの
super.aa()
は、super
を1つのオブジェクトとして使用する.このときsuper
は通常の方法ではa.prototype
を指すので、super.aa()
はa.prototype.aa()
に相当する(クラスのすべての方法はクラスのprototypeに定義され、constructorは除く).注意:superは親のプロトタイプオブジェクトを指すため、親インスタンスに定義されたメソッドまたはプロパティはsuperで呼び出すことはできませんが、プロトタイプに定義されたプロパティおよびメソッドは取得できます(a.prototype.x=233).
class a{
constructor(){
this.x = 1
}
cout(){
console.log(this.x);
}
}
class b extends a{
constructor(){
super();
this.x = 2
}
bd(){
super.cout();
}
}
var c = new b;
b.bd() // 2
以上の結果の出力値は2である、super.cout()はa.prototypeを呼び出します.しかし、aのprototype.cout()バインドbのthisが実際に実行されたのは
super.cout.call(this)
です