我有一个类BMW,它扩展了类Car并覆盖了一个方法printModel:
class Car{
constructor(model){
this.model = model
}
printModel(){
console.log(this.model)
}
}
class BMW extends Car{
constructor(model, color){
super(model);
this.color = color
}
printModel(){
console.log(this.model, this.color)
}
}
let bmw = new BMW('F6', 'blue')
bmw.printModel() //will print : 'F6 blue'
bmw.super.printModel()// expected: 'F6' but not working
如何在这个BMW类的一个实例上调用一个类的超方法?
发布于 2018-09-29 07:47:28
当在实例化上调用某些东西时,您需要一种方法来最终到达super。一种选择是在BMW上定义另一个调用super.printModel的方法
class Car {
constructor(model) {
this.model = model
}
printModel() {
console.log(this.model)
}
}
class BMW extends Car {
constructor(model, color) {
super(model);
this.color = color
}
printModelBMW() {
console.log(this.model, this.color)
}
printModelCar() {
super.printModel();
}
}
let bmw = new BMW('F6', 'blue')
bmw.printModelBMW() //will print : 'F6 blue'
bmw.printModelCar() // expected: 'F6'
发布于 2018-09-29 07:50:18
不可能在类的上下文之外引用超级实例。如果您确实必须从类外部使用来自超级实例的方法,您可以自己调用该方法:
Car.prototype.printModel.call(bmw);发布于 2018-09-29 07:49:42
super关键字只能在类内部使用,不能在外部使用。直接调用Car的printModel方法在技术上是可行的,但这确实应该避免。在超类(如printModel)中重写方法的全部目的是为了给它一个更适合于子类的实现。因此,绕过这一点表明不正确的OO设计。
然而,出于教育目的,我认为知道如何在技术上做到这一点仍然是有用的,因为它揭示了JS类实际上仍然在幕后使用原型:
Car.prototype.printModel.call(bmw)改进设计以避免这种情况的一种方法是添加一个可选参数来指定打印模型的方式:
class BMW extends Car{
constructor(model, color){
super(model)
this.color = color
}
printModel(includeColor){
if (includeColor) {
console.log(this.model, this.color)
}
else super.printModel()
}
}https://stackoverflow.com/questions/52563776
复制相似问题