Why is “this” in an anonymous function undefined when using strict?

99封情书 提交于 2019-11-26 10:21:05

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.

That was terrible behavior and so people at ECMA decided, just to set this to undefined.

Example:

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

The last line would throw an error in ES5 strict

"TypeError: this is undefined"

(which is a much better behavior)

Samuel Rossille

There is a mechanism called "boxing" which wraps or change the this object before entering the context of the called function. In your case, the value of this should be undefined because you are not calling the function as a method of an object. If non strict mode, in this case, this is replaced by the window object. In strict mode it's always unchanged, that's why it's undefined here.

You can find more information at
https://developer.mozilla.org/en/JavaScript/Strict_mode

ReverseTales

According to This Stack Overflow answer, you can use this inside anonymous functions, simply by calling .call(this) at the end of it.

(function () {
    "use strict";

    this.foo = "bar";
}).call(this);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!