javascript - 在子类中调用父类的方法

标签 javascript es6-class

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

如果您有一个 Parent 的父类,其中有 logSomething```` 的 method 和一个 Child 的子类,你用它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.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 调用任何函数或使用父类的任何属性,只要新类没有自己的该属性定义即可。

关于javascript - 在子类中调用父类的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57907775/

相关文章:

javascript - XML 解析错误 : no root element found Location in Console FF

javascript - 复杂选择器在 jQuery 1.8 中中断,但在 1.7.2 中工作

mysql - Node.js ES6 类私有(private)存储

javascript - 为什么 React.Component 的内部实现是一个函数而不是 ES6 类?

javascript - 在 ES6 中添加和删除事件和方法

javascript - 当我单击或在文本区域中键入内容时,为什么 CKEditor 会抛出 JavaScript 错误?

javascript - 在具有不同端口号的单个服务器上运行多个 sails 项目不起作用

javascript - 确保类构造函数中的异步代码在调用类方法之前完成

javascript - 计算出的 JS var 的 NaN 或空白值

javascript - 在React组件中导出方法