Nic*_*k09 0 javascript es6-class
我最近开始学习Classesin javascript,在阅读一些非常有趣的内容时,我想到了尝试自己的一些想法。
如果你有一个父类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
}
Run Code Online (Sandbox Code Playgroud)
当前这样做是行不通的,如果抛出一个错误的事实,那就是您试图定义一个函数的事实。
我知道应该可以以某种方式实现,如果我不误会React使用类似的life-cycle methods权利吗?如componentWillMount。
人们将如何去做呢?
第一个错误是您要扩展Paren而不是Parent。
同样,您不能只在类内部抛出随机语句。它必须在函数内部。
如果您希望它在创建该类的实例时运行,则应在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();Run Code Online (Sandbox Code Playgroud)
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();Run Code Online (Sandbox Code Playgroud)
您也可以这样做:
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();Run Code Online (Sandbox Code Playgroud)
您可以使用调用任何函数或使用父类的任何属性this,只要新类对该属性没有自己的定义。
| 归档时间: |
|
| 查看次数: |
49 次 |
| 最近记录: |