javascript 类中函数调用的that模式,避免this的丢失

本文探讨了JavaScript中使用that模式来解决内部函数this指向问题的方法。通过实例解释了在构造函数和对象字面量中如何利用that变量保持this的正确上下文,避免因默认指向window而引发的错误。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

that模式:就是把类的this赋值给that变量(可以为其他的名字的,只是惯用that而已)


Person = {
	name: "Alice",
	sayName: function() {
		otherSayName = function() {
			alert(this.name);
		};
		otherSayName();
	}
};
Person.sayName();  //在chrome和firefox中是空的

这是由于otherSayName指向Person的this丢失,使得this指向了外部的全部对象window。或者这么说,调用otherSayName的对象是什么都没,则默认是window.otherSayName。所以this会指向window对象。

function Person() {
	this.name = "alice";
	this.sayName = function() {
		otherSayName = function() {
			alert (this.name);
		};
		otherSayName();
	};
}

that模式的修复:

function Person() {
	this.name = "alice";
	this.sayName = function() {
		that = this;
		otherSayName = function() {
			alert (that.name);   //that指向this
		};
		otherSayName();
	};
}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值