0

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?

2
  • $.get(...function(){...}.bind(this)) Commented Feb 28, 2013 at 7:41
  • I can't see why console.log(variable); should show undefined. variables should refer to the constructor argument. Do you pass undefined to the constructor and set this.variable later? Commented Feb 28, 2013 at 7:47

1 Answer 1

4

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");
    }
}
Sign up to request clarification or add additional context in comments.

2 Comments

You can declare self in the constructor as well, since callAjax is a privileged method (declared in the constructor). Your approach is better since it works in prototype methods as well, though.
You're right, I wonder why the first case in the question is not working. It should be working, just the variable will not change.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.