0

I am currently learning jQuery and following many tutorials, almost all of them are using (function(){}(); instead of (function($){}(jQuery); I know the purpose of them are to not create a global var. The thing is I notice I can still use jQuery object inside javascript self executed function, but I can't use them the other way. So why should I use jQuery's self exe func at all?

2
  • 2
    is not for "not create a global var" but for not "use" a global var. Commented Dec 11, 2013 at 8:07
  • Creating global variables is unavoidable. $ (i.e. jQuery) is one, for example. The point is to create as few as possible and then only those that truly are of global usefulness - like library variables. (And even jQuery has .noConflict() because its $ shorthand might clash with other libraries.) Commented Dec 11, 2013 at 8:19

1 Answer 1

1

The premise: is simple comfortable to use $ instead of jQuery.

So $ is a simple shortcut of more verbose jQuery.

However $ is used also for other libraries or it could be used also as simple variable in other part of the project. This is a trick in order to have the certainty of using the $ as jQuery, because the scope chain rule force javascript to take first the value of variable inside your scope, and only if there isn't take the value of the global scope.

Example:

// jQuery is loaded
console.log($ === jQuery) // true

window.$ = {thisIs:"myObject"};

console.log($ === jQuery); // false

(function($) {
    console.log($ === jQuery); // true
})(jQuery);

http://jsfiddle.net/BmkYt/1/

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.