継承に問題があります。ある鉛筆から別の鉛筆への型継承を実装するにはどうすればよいですか?必要:pen3.type //共通
class Pencil {
constructor(color) {
this.color = color;
}
intro() {
console.log(`this is ${this.color} pencil`);
}
};
class SomePencil extends Pencil {
constructor(color, type) {
super(color);
this.type = type;
}
};
class AnotherPencil extends SomePencil {
constructor(color,type) {
super(color, type);
}
};
let pen1 = new Pencil();
let pen2 = new SomePencil("red", "common");
let pen3 = new AnotherPencil("green");
console.log("type" in pen3); // true
継承は、クラス定義自体に設定されていない限り、プロパティのみを継承し、値は継承しません。例えば
class SomePencil extends Pencil {
constructor(color, type) {
super(color);
this.type = type || 'common'; // Setting a default value if type is not passed
}
};
デフォルトを設定する新しい方法
class SomePencil extends Pencil {
constructor(color, type = 'common') {
super(color);
this.type = type;
}
};
jsfiddleを参照してください
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加