3 回答
![?](http://img1.sycdn.imooc.com/545866130001bfcb02200220-100-100.jpg)
TA贡献1847条经验 获得超11个赞
第一个错误是您正在扩展Paren而不是Parent.
你也不能只是在类中抛出一个随机语句。它需要在函数内部。
如果您希望它在创建该类的实例时运行,则它应该位于constructor或 被它调用的函数内。(注意需要super()在构造函数的开头调用,
最后还是需要使用this.logSomethingorthis.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,只要新类对该属性没有自己的定义。
![?](http://img1.sycdn.imooc.com/54584de700017cbd02200220-100-100.jpg)
TA贡献1893条经验 获得超10个赞
看这里了解更多信息。
class Parent {
constructor() {}
logSomething() {
console.log('I am logging something')
}
}
class Child extends Parent {
logSomething() {
super.logSomething(); // Call parent function
}
}
![?](http://img1.sycdn.imooc.com/545862e700016daa02200220-100-100.jpg)
TA贡献1789条经验 获得超10个赞
a) 你不能在那里调用函数,你可以在类中声明的函数中调用函数
b) 你需要使用 this.logSomething()
例子:
class Parent {
constructor() {}
logSomething() {
console.log('I am logging something')
}
}
class Child extends Parent {
fn() {
this.logSomething() // This does work
}
}
new Child().fn()
查看子类中何时fn调用的其他答案logSomething- 然后您需要super.logSomething()调用“父”logSomething 而不是子 logSomething
添加回答
举报