一、常规
被谁调用,this 就指向谁
var myObject = {
foo: "bar",
func: function() {
var self = this;
console.log(this.foo); // bar
console.log(self.foo); // bar
}
};
myObject.func();
上述代码中,func() 是被 myObject 所调用的,调用 func() 时其 this 指向 myObject,而 self 是对 this 对象的拷贝,因此也能正常输出
二、匿名函数自调用
匿名函数统一是被 window 对象所调用的, this 指向 window,但需要注意,其变量作用域仍然是原本的作用域
var myObject = {
foo: "bar",
func: function() {
var self = this;
(function() {
console.log(this.foo); // undefined, this 指向 window
console.log(self.foo); // bar, 变量作用域不变,
//自身找不到 self 变量, 向父级 func() 寻找,
// 进而获得 myObject 的 this 指向
}());
}
};
myObject.func();