javascript高级程序设计阅读收获(10.14.1)——闭包中的this对象

window.identity = 'The Window';

let object = {
	identity:'My Object',
	getIdentityFunc(){
		return function(){
			return this.identity;
		}
	}
}
console.log(object.getIdentityFunc()());//the Window
  1. 内部函数永远不可能直接访问外部函数的this和arguments这两个变量,所以上述代码中的this指向了window对象。
window.identity = 'The Window';

let object = {
	identity:'My Object',
	getIdentityFunc(){
		let that = this;
		return function(){
			return that.identity;
		}
	}
}
console.log(object.getIdentityFunc()());//the Window
  1. 在定义匿名函数之前,先把外部函数的this保存到变量that中,然后在定义闭包时,就可以让他访问到that。
window.identity = 'The Window';

let object = {
	identity:'My Object',
	getIdentity(){
		return this.identity;
	}
};
console.log(object.getIdentity());//My Object
console.log((object.getIdentity)());//My Object
console.log((object.getIdentity = object.getIdentity)());//The Window
  1. 前面两次调用的返回结果是My Object,后面调用的返回结果是The window,因为赋值表达式的值是函数本身,this值不再与任何对象绑定,所以返回的是The Window。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

木子 旭

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值