Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/413.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 从子构造函数调用父方法 类父类{ 构造函数(){ ... } 方法a(){ ... } } 类子级扩展父级{ 构造函数(){ 超级() ... super.methodA()//_Javascript_Ecmascript 6 - Fatal编程技术网

Javascript 从子构造函数调用父方法 类父类{ 构造函数(){ ... } 方法a(){ ... } } 类子级扩展父级{ 构造函数(){ 超级() ... super.methodA()//

Javascript 从子构造函数调用父方法 类父类{ 构造函数(){ ... } 方法a(){ ... } } 类子级扩展父级{ 构造函数(){ 超级() ... super.methodA()//,javascript,ecmascript-6,Javascript,Ecmascript 6,是的,根据您给定的代码,两者都可以工作。但是super.methodA()和这个.methodA()是不同的。如果您从子类重写methodA,您可以看到差异 if child has methodA use super.methodA() else use this.methodA() 这里有一个来自JS站的演示 Gihan:谢谢。这是一个oops。根据问题,孩子没有methodA。问题是从孩子构造函数中调用是否合法,用这两种方式还是其他方式。当然是合法的,你可以通过使用私有字

是的,根据您给定的代码,两者都可以工作。但是
super.methodA()
这个.methodA()
是不同的。如果您从子类重写
methodA
,您可以看到差异

if child has methodA
    use super.methodA()
else
    use this.methodA()
这里有一个来自JS站的演示

Gihan:谢谢。这是一个oops。根据问题,孩子没有methodA。问题是从孩子构造函数中调用是否合法,用这两种方式还是其他方式。当然是合法的,你可以通过使用私有字段来限制访问。现在es6有类似的数据。我不确定私有字段与此有什么关系问题,但无论如何,说“es6有私有字段”是误导性的,因为它们仍然是实验性的,没有得到广泛的支持。嗯,我认为它会起作用,但我得到“MethodA不是函数”不管我怎么做。我想可能是从内部构造函数调用的。请检查演示表单jsbin jsbin非常有说服力,并回答了这个问题,所以我会勾选它。我会做更多的测试,因为这是在web组件定义中。也许它们不同
if child has methodA
    use super.methodA()
else
    use this.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() {

    }
}