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();
};
}