为什么在严格模式下使用javascript时,匿名函数中的this未定义?我理解为什么这是有道理的,但我找不到任何具体的答案。
示例:
(function () {
"use strict";
this.foo = "bar"; // *this* is undefined, why?
}());
小提琴测试:http://jsfiddle.net/Pyr5g/1/查看记录器(firebug)。
这是因为,在ECMAscript 262第5版之前,如果使用constructor pattern
的人忘记使用new
关键字,就会出现很大的混乱。如果您在ES3中调用构造函数时忘记使用new
,那么this
会引用全局对象(浏览器中的window
),并且您会用变量破坏全局对象。
这是一种可怕的行为,因此ECMA的人员决定将this
设置为undefined
。
示例:
function myConstructor() {
this.a = 'foo';
this.b = 'bar';
}
myInstance = new myConstructor(); // all cool, all fine. a and b were created in a new local object
myBadInstance = myConstructor(); // oh my gosh, we just created a, and b on the window object
最后一行将在ES5严格中抛出错误
"TypeError: this is undefined"
(这是一个更好的行为)
有一种称为"装箱"的机制,它在进入被调用函数的上下文之前包装或更改this
对象。在您的情况下,this
的值应该是undefined
,因为您没有将函数作为对象的方法进行调用。如果是非严格模式,在这种情况下,它将被window
对象替换。在strict
模式下,它总是不变的,这就是为什么这里是undefined
。
您可以在
上找到更多信息https://developer.mozilla.org/en/JavaScript/Strict_mode
根据This Stack Overflow的答案,您可以在匿名函数中使用this
,只需在其末尾调用.call(this)
即可。
(function () {
"use strict";
this.foo = "bar";
}).call(this);
严格模式不允许默认绑定,请尝试以下操作:
**yourFunctionName.bind(this)**
我希望现在一切正常。