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.
Example:
(function () {
"use strict";
this.foo = "bar"; // *this* is undefined, why?
}());
Test in a fiddle: http://jsfiddle.net/Pyr5g/1/ Check out the logger (firebug).
It's because, until ECMAscript 262 edition 5, there was a big confusion if people who where using the
constructor pattern
, forgot to use thenew
keyword. If you forgot to usenew
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
toundefined
.Example:
The last line would throw an error in ES5 strict
(which is a much better behavior)
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 ofthis
should beundefined
because you are not calling the function as a method of an object. If non strict mode, in this case, this is replaced by thewindow
object. Instrict
mode it's always unchanged, that's why it'sundefined
here.You can find more information at
https://developer.mozilla.org/en/JavaScript/Strict_mode
According to This Stack Overflow answer, you can use
this
inside anonymous functions, simply by calling.call(this)
at the end of it.