为什么在严格模式下使用javascript时匿名函数中未定义?我理解为什么这可能有意义,但我找不到任何具体的答案。
例子:
(function () {
"use strict";
this.foo = "bar"; // *this* is undefined, why?
}());
在小提琴中进行测试:http: //jsfiddle.net/Pyr5g/1/ 查看记录器(萤火虫)。
为什么在严格模式下使用javascript时匿名函数中未定义?我理解为什么这可能有意义,但我找不到任何具体的答案。
例子:
(function () {
"use strict";
this.foo = "bar"; // *this* is undefined, why?
}());
在小提琴中进行测试:http: //jsfiddle.net/Pyr5g/1/ 查看记录器(萤火虫)。
这是因为,在 ECMAscript 262 第 5 版之前,如果使用 的人constructor pattern
忘记使用new
关键字,就会造成很大的混乱。new
如果您在 ES3 中调用构造函数时忘记使用,请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 strict 中抛出错误
"TypeError: this is undefined"
(这是一个更好的行为)
有一种称为“装箱”的机制,它this
在进入被调用函数的上下文之前包装或更改对象。在您的情况下,值this
应该是undefined
因为您没有将函数作为对象的方法调用。如果是非严格模式,在这种情况下,this 会被window
对象替换。在strict
模式下它总是不变的,这就是它在undefined
这里的原因。
您可以在https://developer.mozilla.org/en/JavaScript/Strict_mode找到更多信息
According to This Stack Overflow answer, you can use this
inside anonymous functions, simply by calling .call(this)
at the end of it.
(function () {
"use strict";
this.foo = "bar";
}).call(this);