为什么是“这个”在使用严格的匿名函数undefined? [英] Why is "this" in an anonymous function undefined when using strict?
问题描述
为什么在严格模式下使用javascript时,匿名函数中的 this 是未定义的?我理解为什么这可能有意义,但我找不到任何具体的答案。
Why is this in an anonymous function undefined when using javascript in strict mode? I understand why this could make sense, but I couldn't find any concrete answer.
示例:
(function () {
"use strict";
this.foo = "bar"; // *this* is undefined, why?
}());
小提琴测试: http://jsfiddle.net/Pyr5g/1/
查看记录器(firebug)。
Test in a fiddle: http://jsfiddle.net/Pyr5g/1/ Check out the logger (firebug).
推荐答案
这是因为,直到ECMAscript 262第5版,如果人们使用构造函数模式
,就会出现很大的混乱,忘了使用新
关键字。如果在ES3中调用构造函数时忘记使用 new
,此
引用了全局对象(窗口
在浏览器中)你会用变量破坏全局对象。
It's because, until ECMAscript 262 edition 5, there was a big confusion if people who where using the constructor pattern
, forgot to use the new
keyword. If you forgot to use new
when calling a constructor function in ES3, this
referenced the global object (window
in a browser) and you would clobber the global object with variables.
这是一种可怕的行为,所以ECMA的人决定,只需将此
设置为 undefined
。
That was terrible behavior and so people at ECMA decided, just to set this
to 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严重中抛出错误
The last line would throw an error in ES5 strict
"TypeError: this is undefined"
(这是一个更好的行为)
(which is a much better behavior)
这篇关于为什么是“这个”在使用严格的匿名函数undefined?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!