Derek 朕會功夫
Derek 朕會功夫

Reputation: 94319

What is the point of doing window.undefined = window.undefined

I was looking at the past versions of jQuery's code, and it seems that in every version they have this line of code somewhere inside:

window.undefined = window.undefined;

I am not able to see why is this important and more importantly, what does this do. This seems like assigning undefined to undefined which makes no sense to me.

However this seems important and I am curious about it.

Upvotes: 16

Views: 2597

Answers (2)

Dagg Nabbit
Dagg Nabbit

Reputation: 76736

window.undefined did not always exist, so code like if (foo === undefined) would throw a ReferenceError in older browsers, because undefined is not defined (i.e. it's not declared). This code just makes sure that undefined is defined (as undefined).

It is sort of unnecessary, though, because there are so many ways to get the value undefined without the eponymous global property. For example you could write if (foo === void 0) or even something like if (foo === [][0]).

Later versions seem to assume that window.undefined exists in all browsers supported. The most recent versions use a pattern like this:

(function( window, undefined ) {
    ...
})( window );

Notice that no value is passed in for undefined, so it's guaranteed to be declared as a local variable, and have a value of undefined.

Upvotes: 10

Mehran Hatami
Mehran Hatami

Reputation: 12961

Using this, jQuery defines a global variable with the real undefined value. having a global variable like myvar means you have this variable in your window scope (like window.mywar), if you run this code in the window scope:

var myvar = "whatever";

javascript defines your variable as if you have run this:

window.myvar = "whatever";

Let's assume we don't have a global variable like myundefined which means window.myundefined does not exist and window.myundefined has no value, it means window.myundefined is really undefined, then you can create a global variable named undefined in your window scope like this:

window.undefined = window.myundefined

and this line has the exact same result as the jQuery code that you have mentioned above. In other words jQuery could have done the same with this code:

window.undefined = window.myundefined

or

window.undefined = window.whatever_you_want_with_no_value

these both define a global variable with no value.

Upvotes: 1

Related Questions