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

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)

Leave a Comment