簡體   English   中英

如果我使用原型創建OOP JS代碼,我如何從循環中引用類方法?

[英]If I create OOP JS code using prototype, how do I reference a class method from a loop?

我先告訴你我的代碼:

function Messages(){
    this.postResponseButton = '#postResponseButton';
    $(document).ready(this.setEvents);
}
Messages.prototype.setEvents = function(){
    $(self.postResponseButton).click(function(){
        this.postResponse(); // ERROR HERE
    });
}
Messages.prototype.postResponse = function(){
    console.log('Post Response');
}
var messages = new Messages();

在標記行(“ERROR HERE”)中,當我將其稱為this.postResponse()時,它無法識別Messages.postResponse()函數。 我也試過self.postResponse()但沒有成功。

我確定這是范圍問題; 我只是不確定如何引用實際對象。 我是否需要設置var me = this並使用它,或者什么?

謝謝你的時間!

正如您所說,問題是click事件處理程序的上下文與它出現的函數不同。 綁定 (ES5,在舊瀏覽器中不起作用)函數this

Messages.prototype.setEvents = function(){
    $(self.postResponseButton).click(function(){
        this.postResponse();
    }.bind(this));
}

或者保存this的引用並使用它:

Messages.prototype.setEvents = function(){
    var that = this;
    $(self.postResponseButton).click(function(){
        that.postResponse();
    });
}

第三種方法是使用$.proxy ,它實際上是Function.prototype.bind的別名,包括舊瀏覽器的后備:

Messages.prototype.setEvents = function(){
    $(self.postResponseButton).click($.proxy(function(){
        this.postResponse();
    }, this));
}

暫無
暫無

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

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