猿问

在子类中从父类调用方法

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


如果你有一个父类Parent中,你有一个method的logSomething```` and a child class of子, with which you do类儿童家长延伸, 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。


怎么做呢?


心有法竹
浏览 181回答 3
3回答

回首忆惘然

第一个错误是您正在扩展Paren而不是Parent.你也不能只是在类中抛出一个随机语句。它需要在函数内部。如果您希望它在创建该类的实例时运行,则它应该位于constructor或 被它调用的函数内。(注意需要super()在构造函数的开头调用,最后还是需要使用this.logSomethingorthis.logSomethingclass 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()调用“父”logSomething 而不是子 logSomething
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答