从 parent class 内 child class 调用方法

Call method from parent class inside child class

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

如果你有 parent class 的 Parent 其中你有 methodlogSomething```` and a child class ofChild, with which you doclass Child 扩展 Parent, how can you then execute the inherited method from the parent class,logSomething```,在 child class?

内部

如果您在 Child class 中定义一个方法并将 this.logSomething() 添加到该方法,只要 child class 中的方法是调用,继承的 logSomething 函数确实会 运行,但除此之外我还没有找到任何方法直接在 child [=49= 内部执行 logSomething ].

我试过 this.logSomething(),我试过将它添加到 object,自执行 (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
此外,您不能只是在 class 中扔一个随机语句。它需要在函数内部。
如果你希望它在你创建 class 的实例时 运行 它应该在 constructor 或它调用的函数中。 (请注意,您需要在构造函数的开头调用 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 调用任何函数或使用父 class 的任何 属性,只要新的 class 没有自己的定义为此 属性.

查看 here 了解更多信息。

class Parent {
  constructor() {}

  logSomething() {
    console.log('I am logging something')
  }

}

class Child extends Parent {
  logSomething() {
    super.logSomething(); // Call parent function
  }

}

a) 你不能在那里调用函数,你可以在 class

中声明的函数中调用函数

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 在 child 中调用 logSomething 的其他答案 class - 那么您需要 super.logSomething() 来调用 "parent" logSomething 而不是 child logSomething