TJ.*_*TJ. 81 javascript anonymous-function use-strict
在严格模式下使用javascript时,为什么这个匿名函数未定义?我理解为什么这可能有意义,但我找不到任何具体的答案.
例:
(function () {
"use strict";
this.foo = "bar"; // *this* is undefined, why?
}());
Run Code Online (Sandbox Code Playgroud)
小提琴测试:http://jsfiddle.net/Pyr5g/1/ 查看记录器(firebug).
jAn*_*ndy 96
这是因为,直到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
Run Code Online (Sandbox Code Playgroud)
最后一行会在ES5严格中引发错误
"TypeError: this is undefined"
Run Code Online (Sandbox Code Playgroud)
(这是一个更好的行为)
Sam*_*lle 15
有一种称为"装箱"的机制,它this在进入被调用函数的上下文之前包装或更改对象.在您的情况下,值this应该是undefined因为您没有将函数作为对象的方法调用.如果是非严格模式,在这种情况下,它将被window对象替换.在strict模式中它始终保持不变,这就是为什么它在undefined这里.
您可以在https://developer.mozilla.org/en/JavaScript/Strict_mode上找到更多信息
小智 6
根据This Stack Overflow的答案,您可以使用this内部匿名函数,只需.call(this)在其末尾调用即可.
(function () {
"use strict";
this.foo = "bar";
}).call(this);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
26393 次 |
| 最近记录: |