90

为什么在严格模式下使用javascript匿名函数中未定义?我理解为什么这可能有意义,但我找不到任何具体的答案。

例子:

(function () {
    "use strict";

    this.foo = "bar"; // *this* is undefined, why?
}());

在小提琴中进行测试:http: //jsfiddle.net/Pyr5g/1/ 查看记录器(萤火虫)。

4

3 回答 3

110

这是因为,在 ECMAscript 262 第 5 版之前,如果使用 的人constructor pattern忘记使用new关键字,就会造成很大的混乱。new如果您在 ES3 中调用构造函数时忘记使用,请this引用全局对象(window在浏览器中),您将使用变量破坏全局对象。

那是可怕的行为,因此 ECMA 的人们决定,只是设置thisundefined.

例子:

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"

(这是一个更好的行为)

于 2012-03-22T12:50:56.380 回答
15

有一种称为“装箱”的机制,它this在进入被调用函数的上下文之前包装或更改对象。在您的情况下,值this应该是undefined因为您没有将函数作为对象的方法调用。如果是非严格模式,在这种情况下,this 会被window对象替换。在strict模式下它总是不变的,这就是它在undefined这里的原因。

您可以在https://developer.mozilla.org/en/JavaScript/Strict_mode找到更多信息

于 2012-03-22T13:00:07.477 回答
11

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);
于 2015-02-13T12:58:30.213 回答