4

在javascript中的以下自定义类中,在回调中,为什么this.obj除了局部变量obj有我想要的东西之外什么都没有?谢谢。

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()
4

2 回答 2

14

因为里面的函数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);
});
于 2013-02-03T07:31:05.350 回答
2

至于这行代码:

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

它起作用的原因与 JavaScript 闭包的工作方式有关。匿名函数中定义的代码可以访问其本地范围内的所有变量以及包含范围内定义的变量,因此obj是可用的。请参阅JavaScript 闭包如何工作?有关关闭的更多信息。

然而,关键字this是对当前范围的引用。因为您是this.obj从匿名函数内部访问的,所以this指的是匿名函数本身 - 它没有obj定义属性。在扩展ClassTest原型的封闭函数中,this指的是当前ClassTest对象,该对象确实obj定义了一个属性。

于 2013-02-03T08:52:44.290 回答