2

This value is set before jQuery has been exposed to the global scope:

_jQuery = window.jQuery, 

Near the end of the IIFE and after the above statement there is

window.jQuery = window.$ = jQuery; 

This is from the jQuery development source.

What compiler mechanism allows jQuery to do an assignment from an unset variable.

Also, what is _jQuery for in general?

4 Answers 4

3

As the comment says, _jQuery backs anything that already exists in the global scope up (like older versions of jQuery). This is probably for the jQuery.noConflict feature.

Sign up to request clarification or add additional context in comments.

6 Comments

so it does not conflict with itself? What else would be stored in window.jQuery?
@HiroProtagonist Well, that depends on whether $.noConflict() is called or not, and how it is called. The line you saw was the set up for the $.noConflict function. The actual function, decides whether or not jQuery gets $ or jQuery in the global namespace. window.jQuery should be only jQuery, unless you pass true in noConflict, in which case, window.jQuery would contain your old version of jQuery.
there must be a check for _jQuery === undefined somewhere, if it had not been set but $.noConflict() was called.
@HiroProtagonist That would probably be needed if jQuery wanted to automatically solve conflicts. In this case, they've provided noConflict where we explicitly say there will be a conflict (or that we just want window.$ free). So here, they just do window.$ = _$, which means, undefined if there was nothing earlier, which means the space is now free for you, or it means that your old library is back to what it was, holding window.$.
well...I don't use defensive coding..but I bet jQuery would.
|
1

That's a way for jQuery to facilitate it's noConflict functionality. It is storing a copy of whatever was set previously to window.jQuery so that it can restore it later if necessary.

Comments

1

That part of the code is preparation for using the $.noConflict() method. window.jQuery is either going to be an existing jQuery library that existed prior to including the one being initialized, or it will be undefined. Neither case should cause a problem.

Comments

1

The answer is in the code:

// Map over jQuery in case of overwrite 

The previous values of window.jQuery and window.$ are saved for the noConflict functionality.

2 Comments

that doesn't make any sense..it's not mapping over jQuery...it's making an assignment to _jQuery...perhaps if they would just have removed the word over it would make sense map possible previous jQuery to _jQuery makes sense.
Probably they are referring to the var's name "jQuery", not to the variable's content. So they map the var "jQuery" - and this is exactly what they do.