为什么在使用strict时,“this”在匿名函数中是undefined?

为什么在严格模式下使用JavaScript时, 是一个匿名函数undefined? 我明白为什么这可能是有道理的,但我找不到具体的答案。

例:

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

在小提琴中testing: http : //jsfiddle.net/Pyr5g/1/检查logging器(萤火虫)。

这是因为,直到ECMAscript 262版本5,如果使用constructor pattern忘记使用new关键字,那么会出现很大的混淆。 如果您在ES3中调用构造函数时忘记使用new ,则会引用全局对象(浏览器中的window ),并且会使用variables来打开全局对象。

那是非常糟糕的行为,所以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对象。 在你的情况下,这个值应该是undefined因为你没有调用函数作为一个对象的方法。 如果是非严格模式,在这种情况下,这个被window对象取代。 在strict模式下,它始终保持不变,这就是为什么在这里undefined

你可以find更多的信息
https://developer.mozilla.org/en/JavaScript/Strict_mode

根据这个堆栈溢出的答案 ,你可以使用this匿名函数,只需在它的结尾调用.call(this)

 (function () { "use strict"; this.foo = "bar"; }).call(this); 
Interesting Posts