How is data passed to anonymous functions in JavaScript?

When I pass 'this' to an anonymous function, for example:

MyClass.prototype.trigger = function(){
    window.setTimeout(function(){this.onTimeout();},1000);
}

I get "this.onTimeout not function" -error. I assume that 'this' is no longer available at the time the anonymous function is executed? So I do this:

MyClass.prototype.trigger = function(){
    var me = this
    window.setTimeout(function(){me.onTimeout();},1000);
}

Is this the way you should do something? It seems to work, but it is strange.

Then we have the following example:

$(function(){
    function MyClass(){
        this.queue = new Array();
    }
    MyClass.prototype.gotAnswer = function(count){
        $('body').append("count:"+count+"<br/>");
    }
    MyClass.prototype.loadAll = function(){
        var count = 0;
        var item;
        while(item = this.queue.pop()){
            count++;
            var me = this;
            $.getJSON("answer.html",{},function(data){me.gotAnswer(count);});
        }
    }

    var o = new MyClass();
    o.queue.push(1);
    o.queue.push(2);
    o.loadAll();

});

It is output:

2
2

Should not be output:

1
2

instead of this? Then I found that including the $ .getJSON expression in another function makes everything work:

MyClass.prototype.loadAll = function(){
    var count = 0;
    var item;
    while(item = this.queue.pop()){
        count++;
        this.newRequest(count);
    }
}
MyClass.prototype.newRequest = function(count){
    var me = this;
    $.getJSON("answer.html",null,function(data){ me.gotAnswer(count); });
}

It is output:

1
2

(Or vice versa). What's going on here? What is the correct way to pass variables into an anonymous function?

Sorry for the confusing and lengthy post.

+5
source share
3

, , - - , . "this" reset . , "this".

  • myFunc(param1, param2);
    reset "this" . .
  • myObj.myFunc(param1, param2);
    "this" , . "this" == "myObj".
  • invocation
    myFunc.apply(myObj, [param1, param2])
    : "this" , apply - , ( , ). apply.
  • ( "" )
    myNewObj = new MyConstructor(param1, param2);
    , "this" , . MyConstructor.prototype. , , "this".

, , - "this" , . , , - "", , - - .

+5

.

, , , , . , that, this.

MyClass.prototype.trigger = function(){
    var that = this;
    window.setTimeout(function(){that.onTimeout();},1000);
}

StackOverflow . javascript?.

- Javascript - .

+3

you will have the same problem if inside your new method: newRequest you should use the pros or the statement. Another solution could be to create a closure:

like this:

$.getJSON("answer.html",{},(function(me){return function(data){me.gotAnswer(count);}})(this));
0
source

All Articles