如何在类外调用超类方法?

时间:2018-09-28 23:40:59

标签: javascript node.js class oop ecmascript-6

我有一个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类的实例上调用类超级方法?

5 个答案:

答案 0 :(得分:1)

在实例化上调用某些内容时,您将需要一种最终到达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'

答案 1 :(得分:1)

不可能在类的上下文之外引用超级实例。如果确实必须从类外部使用超级实例中的方法,则可以自己调用该方法:

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()
    }
}

答案 2 :(得分:0)

super关键字只能在类内部使用,而不能在外部使用。从技术上讲,可以直接调用Car的{​​{1}}方法,但这确实应该避免。覆盖超类(例如printModel)中方法的全部目的是为它提供一个更适合于子类的实现。因此,规避这表明OO设计不正确。

但是,出于教育目的,我认为了解技术上的实现方式仍然很有用,因为它揭示了JS类实际上仍在使用原型的情况:

printModel

一种避免这种情况的改进设计的方法是添加一个可选参数来指定您要如何打印模型:

Car.prototype.printModel.call(bmw)

答案 3 :(得分:0)

class Car{
    constructor(model){
       this.model = model
    }
    printModel(){
    console.log(this.model)
    }
   getModel()
  {
      return this.model
  }

 }

  class BMW extends  Car{
      constructor(model, color){
        super(model);
         this.color = color
     }
     printModel(){
         console.log(super.getModel(), this.color)
     }
}

答案 4 :(得分:0)

如果父类方法需要与子类方法一起使用,则表明类设计出错,覆盖父方法是一个错误。

可能是:

class Car{
    ...
    printGenericModel(){
        console.log(this.model)
    }
}

class BMW extends Car{
    ...
    printModel(){
        console.log(this.model, this.color)
    }
}

或者如果无法重构父类:

class Car{
    ...
    printModel(){
        console.log(this.model)
    }
}

class BMW extends Car{
    ...
    get printGenericModel(){
        return super.printModel;
    }
    printModel(){
        console.log(this.model, this.color)
    }
}

这两种方法在printGenericModel实例上都可以作为printModelBMW使用。

相关问题