簡體   English   中英

從子構造函數調用父方法

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM