How is data passed to anonymous functions in JavaScript?

后端 未结 3 2120
萌比男神i
萌比男神i 2021-02-10 03:01

When I pass \'this\' to an anonymous function like so:

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


        
3条回答
  •  情话喂你
    2021-02-10 03:22

    You are confused about the closures.

    For the first problem, yes, you are right, that is the way it can be done. The only difference that there is a convention to name the variable that that holds this.

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

    There is already a nice thread about this on StackOverflow. Check answers for question How does a javascript closure work?.

    Your second problem is an exact duplicate of Javascript closure inside loops - simple practical example.

提交回复
热议问题