先看下习题:
var myObject = {
foo:'bar',
func:function(){
var self = this;
console.log(this.foo); // bar
console.log(self.foo); // bar
(function(){
console.log(this); // 该this指向的是 window
console.log(this.foo); // undefined
console.log(self.foo); // bar
}());
}
}
myObject.func();
解析:
前两个 console ,this指向的是 myObject ,所以打印出的是 bar。
在后面的闭包里面,this 指向的是window,而self 是被赋过值的,因此 self.foo 是bar,this.foo 是undefined(因为这里this指向的是window)。