Why is "this" in anonymous function undefined when using strict?

Why is this in anonymous function undefined when using javascript in strict mode? I understand why this might make sense, but I have not found a specific answer.

Example:

(function () { "use strict"; this.foo = "bar"; // *this* is undefined, why? }()); 

Test in the script: http://jsfiddle.net/Pyr5g/1/ Check the registrar (firebug).

+65
javascript use-strict anonymous-function
Mar 22 '12 at 12:45
source share
3 answers

This is because, before ECMAscript 262 edition 5, there was a lot of confusion if people using the constructor pattern forgot to use the new keyword. If you forgot to use new when invoking the constructor function in ES3, this referred to the global object ( window in the browser), and you would have attached the global object to variables.

This was terrible behavior, and so people at ECMA decided 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 will output an error in ES5 strict

 "TypeError: this is undefined" 

(which is much better)

+76
Mar 22 '12 at 12:50
source share
β€” -

There is a mechanism called β€œboxing” that wraps or modifies this object before entering the context of the called function. In your case, this should be undefined because you are not calling the function as an object method. If the mode is not strict, in this case, it is replaced by the window object. In strict mode, it always remains unchanged, so it is undefined here.

More information can be found at https://developer.mozilla.org/en/JavaScript/Strict_mode

+11
Mar 22 '12 at 13:00
source share

In accordance with

+5
Feb 13 '15 at 12:58
source share



All Articles