在我的一些 Javascript 对象中,我发现我的this
指针是正确的 - 这些是new Func()
-type 对象 - 创建时,但在分配的方法中可能是错误的。
function Confused() {
console.log("checking",this==window,"is always false");
this.method = function() {
console.log("checking",this==window,"is true for some funcs but not others");
};
};
在某些电话中(new Confused()).method()
- 似乎已经失去了它this
指针。这种情况发生的次数似乎取决于函数,而不是随机的;它是关于我如何创建导致此问题的类的代码中的某些内容。
在线示例位于http://williame.github.com/barebones.js/ http://williame.github.com/barebones.js/和成员回调G3D._file_loaded https://github.com/williame/barebones.js/blob/d313f04dceba0b9c9125501661728e1908a2d026/g3d.js#L10有一个错误this
有时调用时的指针。
为什么会这样,我该如何解决?
在 Javascript 中有 4 种使用函数的方法
其中每一个的作用是改变内容的内容this
is :
- 函数调用: this = 全局对象(浏览器中的窗口)
- 方法调用: this = 调用它的对象。
- 构造函数调用: this = 您正在创建的新对象。
- 调用/应用调用: this = 您传递的对象。
在你的情况下this == window
当您直接调用该函数时(Confused()
) 但如果你使用 new (new Confused()
)那么它将是您正在创建的新对象。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)