簡體   English   中英

我應該用哪種方式在 Javascript 中調用繼承的靜態方法?

[英]Which way should I call an inherited static method in Javascript?

當 JavaScript 中的類擴展具有靜態方法的類時,可以通過從 Parent 類或 Child 類引用它來調用該方法,結果看起來相同,但它們之間有什么區別嗎?

例子:

class MyParentClass {
    static myFunction() {};
}

class MyChildClass extends MyParentClass {
    anotherFunction() {
        MyParentClass.myFunction();
        MyChildClass.myFunction();
    }
}

MyParentClass.myFunction(); MyChildClass.myFunction(); 兩者都會導致調用相同的函數。 我應該使用一個而不是另一個,還是根本沒有區別?

當您調用parent.foo();時,解釋很簡單parent.foo(); 您通過調用child.foo();來調用該函數的父級實現child.foo(); 你正在調用孩子的實現。

如果您只想調用父類的函數而不覆蓋子類中的方法,則兩種調用之間確實沒有區別。 但是在這個例子中有:

class Parent {
    static foo() {
        console.log("Parent");
    }
}

class Child extends Parent {
    static foo() {
        console.log("Child");
    }

    bar() {
        Parent.foo(); // will print "Parent" to the console
        Child.foo(); // will print "Child" to the console
    }
}

從這個例子來看,我建議總是調用child.foo()來更容易維護代碼。 如果將覆蓋函數foo()在未來,呼吁parent.foo()但希望的結果child.foo()它會帶你一段時間才能發現其中的錯誤。

如果您明確需要父級實現的結果,您應該只調用parent.foo()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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