![](/img/trans.png)
[英]How to call a constructor method of Parent class from child prototype in javascript?
[英]call parent method from child constructor
class Parent{
constructor(){
...
}
methodA(){
...
}
}
class Child extends Parent{
constructor(){
super()
...
super.methodA() // <=== ok ???
this.methodA() // <=== ok ???
}
}
如果不合法,建议解决方法?
我认为这个问题是不言而喻的,但这个网站想要更多的文字,所以在这里。
是的,根据您给定的代码,两者都有效。 但是super.methodA()
和this.methodA()
是不同的。 如果您覆盖子类中的methodA
,您可以看到不同之处。
class Child extends Parent{
constructor(){
super()
...
super.methodA() // this calls the Parent class's methodA
this.methodA() // this will call the Child class's methodA
}
methodA() {
}
}
这是来自 JS bin https://jsbin.com/zisamideyu/edit?js,console的演示
if child has methodA
use super.methodA()
else
use this.methodA()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.