为什么是“这个"?在匿名函数中使用严格时未定义? [英] 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/检查记录器(萤火虫).
Test in a fiddle: http://jsfiddle.net/Pyr5g/1/ Check out the logger (firebug).
推荐答案
这是因为,直到 ECMAscript 262 第 5 版,如果使用 构造函数模式
的人忘记使用new
关键字.如果在 ES3 中调用构造函数时忘记使用 new
,this
引用了全局对象(浏览器中的 window
)带有变量的全局对象.
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 的人决定,将 this
设置为 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)
这篇关于为什么是“这个"?在匿名函数中使用严格时未定义?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!