【问题标题】:Getting correct "this" in jQuery button callback在 jQuery 按钮回调中获取正确的“this”
【发布时间】:2010-11-10 19:32:09
【问题描述】:

我有一堂课:

function RustEditor() {

this.init = function() {

    var saveButton = this.container.find("button.saveButton");
    saveButton.click(function(){this.save();});

};
...

当我点击按钮时,它抱怨 this.save 不是一个函数。这是因为这里的“this”不是指RustEditor 的实例,而是指按钮。我可以在回调闭包中使用什么变量来指向 RustEditor 的实例?我可以使用 rust.editor(它是全局范围内的名称),但那是臭代码。

【问题讨论】:

    标签: javascript oop this


    【解决方案1】:

    通常的做法是像这样将this 值括起来:

     function RustEditor() {
    
     this.init = function() {
        var self = this;
    
        var saveButton = this.container.find("button.saveButton");
        saveButton.click(function(){self.save();});
    
     };
    

    根据 tvanfosson 的建议进行更新this 在事件处理程序被调用时被反弹,因此您需要在创建对象时捕获对类的引用,该变量将在闭包中保留该引用。

    【讨论】:

    • 如果您能解释为什么会发生这种情况,这将改善您的答案,也就是说,当调用事件处理程序时 this 会反弹,因此您需要捕获引用在创建对象时使用将在闭包中保留该引用的变量到类。
    • @tvanfosson - 感谢您的建议。希望你不介意我逐字引用你。你说的比我好。
    【解决方案2】:

    在 RustEditor() 中,您可以首先复制对按钮的引用并使用它。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-12-30
      相关资源
      最近更新 更多