javascript 类中函数调用的that模式,避免this的丢失
2013-03-30 17:52
567 查看
that模式:就是把类的this赋值给that变量(可以为其他的名字的,只是惯用that而已)
这是由于otherSayName指向Person的this丢失,使得this指向了外部的全部对象window。或者这么说,调用otherSayName的对象是什么都没,则默认是window.otherSayName。所以this会指向window对象。
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调用模式(this的取值)以及,call(),apply()函数浅析
- <javascript>this不同调用模式引起的问题,函数内部调用函数this无效
- javascript的四种函数调用模式以及相应的this绑定
- javascript this 关键字以及四种函数调用模式
- javascript语言精粹学习笔记之函数的四种this调用模式
- javascript中四种函数调用模式及对this的不同绑定
- 【百度分享】javascript中函数调用过程中的this .
- 函数的四种调用模式(this的指向)
- JavaScript中七种函数调用方式及对应 this 的含义
- JavaScript中七种函数调用方式及对应 this 的含义
- javascript的四种函数调用模式
- Javascript 的函数调用模式,有意思的表现
- JavaScript中函数的四种调用模式
- javascript 函数的4种调用模式
- javascript this 代表的上下文,JavaScript 函数的四种调用形式
- JavaScript—在嵌套的内部函数中调用外部this的方法
- <a href="javascript:"里面调用的函数的参数this无效
- JavaScript中函数参数this及函数调用
- 函数四种调用模式以及this指向
- JavaScript中七种函数调用方式及对应 this 的含义