为什么使用strict时未定义匿名函数中的“ this”?

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


例:


(function () {

    "use strict";


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

}());

在小提琴中测试:http : //jsfiddle.net/Pyr5g/1/ 检查记录器(firebug)。


茅侃侃
浏览 610回答 3
3回答

郎朗坤

这是因为,在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 objectmyBadInstance  = myConstructor(); // oh my gosh, we just created a, and b on the window object最后一行会在严格的ES5中引发错误"TypeError: this is undefined"(这是一个更好的行为)
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript