继承有问题。如何实现从 Some Pencil 到 Another Pencil 的类型继承?需要:pen3.type//common
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
关于javascript - 我怎样才能实现继承链?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53285056/