何らかの継承を計画している場合は、をお勧めしthis.constructorます。この単純な例は、その理由を説明しているはずです。
class ConstructorSuper {
constructor(n){
this.n = n;
}
static print(n){
console.log(this.name, n);
}
callPrint(){
this.constructor.print(this.n);
}
}
class ConstructorSub extends ConstructorSuper {
constructor(n){
this.n = n;
}
}
let test1 = new ConstructorSuper("Hello ConstructorSuper!");
console.log(test1.callPrint());
let test2 = new ConstructorSub("Hello ConstructorSub!");
console.log(test2.callPrint());
test1.callPrint()ConstructorSuper Hello ConstructorSuper!コンソールに記録します
test2.callPrint()ConstructorSub Hello ConstructorSub!コンソールに記録します
名前付きクラスを参照するすべての関数を明示的に再定義しない限り、名前付きクラスは継承をうまく処理しません。次に例を示します。
class NamedSuper {
constructor(n){
this.n = n;
}
static print(n){
console.log(NamedSuper.name, n);
}
callPrint(){
NamedSuper.print(this.n);
}
}
class NamedSub extends NamedSuper {
constructor(n){
this.n = n;
}
}
let test3 = new NamedSuper("Hello NamedSuper!");
console.log(test3.callPrint());
let test4 = new NamedSub("Hello NamedSub!");
console.log(test4.callPrint());
test3.callPrint()NamedSuper Hello NamedSuper!コンソールに記録します
test4.callPrint()NamedSuper Hello NamedSub!コンソールに記録します
上記すべてをBabel REPLで実行しているところを見てください。
test4これからも、スーパークラスにあると考えていることがわかります。この例では大したことのようには見えないかもしれませんが、オーバーライドされたメンバー関数または新しいメンバー変数を参照しようとすると、問題が発生します。
SomeObject.print自然に感じます。しかしthis.n、静的メソッドの場合、インスタンスがないため、内部は意味がありません。