Getting the "this" correct in a 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 due to the fact that "this" here does not refer to an instance of RustEditor, but to a button. Which variable can I use inside this callback closure to point to a RustEditor instance? I could use rust.editor (it's a name in the global scope), but this smelly code.

+3
source share
2 answers

It is common practice to attach a value thisas follows:

 function RustEditor() {

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

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

 };

tvanfosson: this , , , .

+12

RustEditor() .

+1

Source: https://habr.com/ru/post/1712611/


All Articles