我最近开始学习 javascript
中的类
,在阅读一些非常有趣的内容时,我想到尝试一些自己的想法。
如果您有一个 Parent
的父类,其中有 logSomething```` 的
Child 的子类method
和一个 ,你用它
class Child extends Parent,那么你如何在子类内部执行从父类继承的方法,
logSomething```? p>
如果您在 Child
类内部定义一个方法,并将 this.logSomething()
添加到该方法中,则每当调用子类中的方法时,继承的方法都会被调用。 logSomething
函数确实会运行,但除此之外,我还没有找到任何直接在该子类内部执行 logSomething
的方法。
我尝试过 this.logSomething()
,我尝试过将其添加到对象、自执行 (IIFE) 函数以及我能想到的一切,但没有结果。
class Parent {
constructor() {}
logSomething() {
console.log('I am logging something')
}
}
class Child extends Paren {
logSomething() // This does not work
}
目前这样做不起作用,如果抛出一个错误,表明它与您尝试定义函数有关。
我知道这应该以某种方式是可能的,如果我没有弄错React
使用与生命周期方法
类似的东西,对吧?例如componentWillMount
。
如何去做这件事?
最佳答案
第一个错误是您扩展了 Paren
而不是 Parent
。
此外,您不能只是在类中添加随机语句。它需要位于函数内部。
如果您希望它在创建该类的实例时运行,它应该位于构造函数或由它调用的函数内。 (请注意,您需要在构造函数的开头调用 super()
。
最后,您仍然需要使用 this.logSomething
或 this.logSomething
class Parent {
constructor() {}
logSomething() {
console.log('I am logging something');
}
}
class Child extends Parent {
constructor() {
super();
this.logSomething(); // Will use Parent#logSomething since Child doesn't contain logSomething
super.logSomething(); // Will use Parent#logSomething
}
}
new Child();
class Parent {
constructor() {}
logSomething() {
console.log('Parent Logging Called');
}
}
class Child extends Parent {
constructor() {
super();
this.logSomething(); // Will call Child#logSomething
super.logSomething(); // Will call Parent#logSomething
}
logSomething() {
console.log('Child Logging Called');
}
}
new Child();
您也可以这样做:
class Parent {
constructor() {}
logSomething() {
console.log('Parent Logging Called');
}
}
class Child extends Parent {
logSomething() {
console.log('Child Logging Called and ...');
// Careful not use this.logSomething, unless if you are planning on making a recursive function
super.logSomething();
}
}
new Child().logSomething();
您可以使用 this
调用任何函数或使用父类的任何属性,只要新类没有自己的该属性定义即可。
关于javascript - 在子类中调用父类的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57907775/