reizals
reizals

Reputation: 1335

javascript variable scope in callbacks

I'm curious how could this be written better:

function Klass(variable) {
    this.variable = variable;

    this.callAjax = function() {
        $.get('/url', { }, function(json) {
            console.log(variable); //! <-- shows undefined
        }, "json");
    }
}

so I create a local variable: _variable

function Klass(variable) {
    this.variable = variable;

    this.callAjax = function() {
        var _variable = this.variable;
        $.get('/url', { }, function(json) {
            console.log(_variable); //! <-- its ok
        }, "json");
    }
}

and its fine, but I really don't this solutions,

Does someone of you have a better code?

Upvotes: 0

Views: 500

Answers (1)

Min Lin
Min Lin

Reputation: 3197

That's quite the way.

function(json){console.log(_variable);} 

forms a closure with "_variable". "_variable" keeps the original value forever.

If your "variable" should be updated later, and you want the updated "variable" You define

var self = this; 

and call self.variable to get it.

In this way you'll get the updated "variable" each time the callback is executed.

The complete code:

function Klass(variable) {
    var self = this;
    this.variable = variable;
    this.callAjax = function() {
        $.get('/url', { }, function(json) {
            console.log(self.variable);
        }, "json");
    }
}

Upvotes: 4

Related Questions