您的位置:首页 > Web前端 > JavaScript

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

2013-03-30 17:52 567 查看
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();
};
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: