简体   繁体   中英

Getting correct “this” in jQuery button callback

I have a class:

function RustEditor() {

this.init = function() {

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

};
...

When I click the button, it complains that this.save is not a function. This is because "this" does not refer to the instance of RustEditor here, but to the button. What variable can I use inside that callback closure to point to the instance of RustEditor? I could use rust.editor (it's name in the global scope) but that's smelly code.

Common practice is to enclose the this value like so:

 function RustEditor() {

 this.init = function() {
    var self = this;

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

 };

Update with suggestion from tvanfosson : this gets rebound when the event handler is invoked and thus you need to capture the reference to the class at the time the object is created with a variable that will retain that reference in the closure.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM