从子类中的父类调用方法



我最近开始在javascript中学习Classes,在阅读一些非常有趣的东西时,我想尝试一些我自己的想法。

如果您有一个父类Parent其中您有logSomething```` and a child class of子类, with which you do类子类的method子类扩展父类, how can you then execute the inherited method from the parent class,logSomething'',在子类内部?

如果在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使用类似的东西life-cycle methods对吧?比如componentWillMount.

一个人该怎么做呢?

第一个错误是你正在扩展Paren而不是Parent
此外,您不能只是在类中随机抛出一个语句。它需要位于函数内部。
如果您希望它在创建该类的实例时运行,它应该位于constructor或由它调用的函数中。(请注意,您需要在构造函数的开头调用super()
最后,您仍然需要使用this.logSomethingthis.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调用任何函数或使用父类的任何属性,只要新类对该属性没有自己的定义。

查看此处以获取更多信息。

class Parent {
constructor() {}
logSomething() {
console.log('I am logging something')
}
}
class Child extends Parent {
logSomething() {
super.logSomething(); // Call parent function
}
}

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()调用"parent"logSomething而不是子logSomething

最新更新