**
1.全局下的this指向window
**
console.log(this) //全局环境下this指向window
**
2.函数独立调用下的this指向window
**
function fn(){
console.log(this) //函数独立调用,函数内部this指向window
}
fn();
**
3.函数当做对象的方法调用,this指向obj
**
var a=1;
var obj = {
a:2,
foo:function(){//函数当做对象的方法来调用,this指向obj
function test(){
var that=this
console.log(this); //this指向window,因为obj.foo() 一调用,test它就会自己执行,这就相当于函数独立调用,所以指向的是window
console.log(that.a) //输出2
}
test();
}
}
obj.foo()
**
4.自执行函数this指向window
**
(function(){
console.log(this)
})()
**
5.闭包 this默认指向window
**
var a=0;
var obj={
a:2,
foo:function(){
c=this.a
return function test(){
console.log(this)//指向window
console.log(c) //结果为2
return a
}
}
}
var fn=obj.foo()
console.log(fn())//输出a的值为0