簡體   English   中英

如何從對象內部調用類函數?

[英]How can I call a class function from inside an Object?

我試圖從存儲在同一個類的另一個函數中的對象內部調用一個類的函數。 我不能使用this ,因為它是指對象而不是類。 直接調用函數名稱也不起作用,因為它會引發“未定義”錯誤。

我有與此等效的代碼:

class X extends Y {
    functionA() {
        console.log("Function called!");
    }
    functionB() {
        window.testObject = {
            objectFunction() {
                // I need to call functionA from inside here
            }
        }
    }
}

如何從objectFunction內部調用functionA

你可以簡單地設置另一個變量(例如, self )等於this之前, this變化。

class X extends Y {
    functionA() {
        console.log("Function called!");
    }
    functionB() {
        let self = this;
        window.testObject = {
            objectFunction() {
                // I need to call functionA from inside here
                self.functionA();
            }
        }
    }
}

暫無
暫無

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

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