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

被折叠的 条评论
为什么被折叠?



