A this reference problem in a callback function

57 1
var obj = {
//我想让this指代上面这个obj
 a:function(){
 setTimeout(function(){
 console.log(this);
 },100);
 },
//好吧,曲折解决了
 b:function(){
 var me = this;
 setTimeout(function(){
 console.log(me);
 },100);
 },
//如果我要把callback拿出来,又有问题了。。。
 c:function(){
//这下不管我怎么在c和callback里倒来倒去的找变量,都不能在callback里找到最上面的那个obj了。。
 setTimeout(this.callback,100);
 },
 callback:function(){
 console.log(this);//我需要在这里找到obj..
 }
};
obj.a();
//obj.b();
//obj.c();
10 Answers

66 1

A atrl approach solves the problem of stripping the callback function and maintaining this references.
This method can be used in more advanced browsers:

c:function(){
 setTimeout(this.callback.bind(this),100);
 }

The prototype implementation of the function object can be extended by browser such as ie. But the idea is to create a new function.

Here's the need to do this. Sometimes there's a need to decouple the event handler, because it's more complex to consider, and you need to write your own objects.

75 3
134 0
105 3
...