最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Getting correct "this" in jQuery button callback - Stack Overflow

programmeradmin0浏览0评论

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 plains 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.

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 plains 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.

Share Improve this question asked Jul 14, 2009 at 21:11 Bart van HeukelomBart van Heukelom 44.1k62 gold badges191 silver badges307 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 12

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.

Within RustEditor() you could first copy a reference to the button and use that.

发布评论

评论列表(0)

  1. 暂无评论