我正在学习 ES6 类和对象。为此,我正在制作一个示例应用程序,我发现了这个问题:
我有这个主类:
class App {
boot() {
console.log('app booted')
}
}
然后我有另一个类,它从第一个类扩展而来:
class someClass extends App {
boot() {
this.update()
}
update() {
console.log('update Method!')
}
}
从 someClass
我正在覆盖启动方法。这工作正常,因为它正在尝试调用 update
方法。
但它返回 update
方法为 undefined
。
我明白了,在本例中,this
是 App
类,因此 update
在 App
内部未定义.
有没有办法从 someClass
类中的 boot
方法调用 update
方法?
最佳答案
是的,有。实例化一个新对象,然后对该对象调用 boot()
。例如像这样:
class App {
boot() {
console.log('app booted')
}
}
class someClass extends App {
boot() {
this.update()
}
update() {
console.log('update Method!')
}
}
const test = new someClass();
test.boot(); // update Method!
您可以测试您的代码here .
关于javascript - ES2015 : Call Inner method from overwrited class,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36818762/