2013-02-03 98 views
4

在下面的javascript中的自定义类中,在回调函数中,为什么this.obj只有局部变量obj有我想要的东西?谢谢。javascript如何在回调函数中获得this.variable

function ClassTest(director) { 
    this.obj = {"test1": "test1"}; 
} 

function test1(input, callback) { 
    callback("success"); 
} 

ClassTest.prototype.test = function() { 
    var obj = this.obj; 
    test1("niuniu",function(e){ 
    console.log(this.obj); // undefined 
    console.log(obj); // this one has stuff 
    }); 
} 

// run 
new ClassTest().test() 
+1

添加'var that = this;',然后在回调中使用'that'来引用'this' :) –

回答

13

由于内部test1该函数创建具有不同this上下文一个新的范围。典型的解决方案是bind或缓存this

绑定:

test1("niuniu",function(e){ 
    console.log(this.obj); 
}.bind(this)); 

缓存:

var self = this; 
test1("niuniu",function(e){ 
    console.log(self.obj); 
}); 
2

至于这行代码:

console.log(obj); // this one has stuff 

它的工作原理的原因与JavaScript关闭如何工作有关。在您的匿名函数中定义的代码可以访问其本地范围中的所有变量以及在包含范围中定义的变量,因此obj可用。有关更多关闭,请参阅How do JavaScript closures work?

但是,关键字this是对当前范围的引用。因为您正在从匿名函数内访问this.obj,因此this引用了匿名函数本身 - 它没有定义obj属性。在扩展ClassTest原型的封装函数中,this引用当前的ClassTest对象,该对象确实具有obj属性。