1.全局环境下的this
console.log(this);
结果:
结论:全局环境下的this指向了window
2.函数独立调用,函数内部的this
function fn(){
console.log(this)
}
fn()
结果:
结论:函数独立调用,函数内部的this也指向了window
3.被嵌套的函数独立调用时,this指向
var a = 0;
var obj = {
a:2,
foo:function(){
//函数被当作对象的方法来调用 this指向了obj
var that = this;
function test(){
console.log(this) //指向window
console.log(that) //指向函数对象
}
test();
}
}
obj.foo();
结果:
结论:被嵌套的函数独立调用时,this默认指向了window
4.IIFE 自执行函数(立即执行函数)中内部的this指向
var a = 10;
function foo(){
console.log('1'+this); //指向对象
(function test(){
console.log('2'+this) //指向window
})()
}
(function test(that){
console.log(3+that) //通过传入参数this,指向就变成对象obj
})(this)
var obj = {
a:2,
foo:foo
}
obj.foo();
(function(){
console.log('自执行函数中的内部this:'+this);
})()
结果:
结论:IIFE 自执行函数(立即执行函数)中内部的this指向了window
5.闭包中 this指向
var a = 0;
var obj = {
a:2,
foo:function(){
var c = this.a;
console.log(this) //指向函数对象
return function test(){
console.log(this) //闭包函数里面的this指向window
return c;
}
}
}
var fn = obj.foo();
console.log(fn())
结果:
结论:闭包中 this默认指向了window