this指向的理解

**

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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值