簡體   English   中英

從同一個類中的另一個方法調用javascript類方法

[英]Calling javascript class methods from another method inside the same class

我不知道該如何處理。 我有一個像這樣的Javascript對象:

var myClass = {

    init : function(){
        $("button").on("click" , this.func1);
    },

    func1: function(){

        // do stuffs

        this.func2();

    },

    func2: function(){

        // do stuffs
    }
}

myClass.init();

當我為綁定事件初始化我的類時,沒有問題。 在init函數中, this的值是類本身,因此我可以毫無問題地調用它們的方法。

考慮到單擊按鈕時,我執行了func1 我發現在函數內部問題func1 ,因為在這種情況下的價值this是被按下的按鈕,所以當我嘗試this.func2我得到Uncaught TypeError: this.func2 is not a function

我該如何處理此類問題? 我敢肯定有解決這個問題的標准方法,但我不知道。

謝謝 !!

從您的示例來看, this.func1在執行時實際上沒有任何上下文綁定。 因此,它的this關鍵字將在legacy mode下回退到window對象,或者在strict mode legacy mode undefined 為了在myClass上下文中執行this.func1 ,可以使用以下方法之一:

  1. 使用Function.prototype.bind this設置為myClass

     $("button").on("click", this.func1.bind(this)); 
  2. 包裝在匿名函數中

     var self = this; $("button").on("click", function() { self.func1(); }); 
  3. 包裝在箭頭功能內

     $("button").on("click", () => this.func1()); 

暫無
暫無

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

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