Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the purpose of this? (function ($) { //function code here })(jQuery);

I am debugging someone else's JavaScript code and a majority of the code is wrapped like this:

(function ($) {
    //majority of code here...
})(jQuery);

What is going on with the ($) and the (jQuery)? I wasn't taught to code like that and haven't seen them. What is their purpose?

As well, there is no document.ready, but I assume that is because the code is executed right after it's read by the (); at the end?

like image 368
tsdexter Avatar asked Nov 29 '11 03:11

tsdexter


People also ask

What does function ($) mean in jQuery?

(function($) { // do something })(jQuery); this means, that the interpreter will invoke the function immediately, and will pass jQuery as a parameter, which will be used inside the function as $ .

What is ($) in JavaScript?

The Dollar ($) IdentifiergetElementById(). Because this function is fairly verbose and used frequently in JavaScript, the $ has long been used as its alias, and many of the libraries available for use with JavaScript create a $() function that references an element from the DOM if you pass it the id of that element.

What is .ready in jQuery?

jQuery ready() MethodThe ready event occurs when the DOM (document object model) has been loaded. Because this event occurs after the document is ready, it is a good place to have all other jQuery events and functions. Like in the example above. The ready() method specifies what happens when a ready event occurs.

Why this is used in jQuery?

HTML. The this Keyword is a reference to DOM elements of invocation. We can call all DOM methods on it. $() is a jQuery constructor and in $(this), we are just passing this as a parameter so that we can use the jQuery function and methods.


1 Answers

var $ = "some value we don't care about";

 // v=====normal plain old function
(function ($) {
 //        ^=======receives jQuery object as the $ parameter

    //majority of code here, where $ === jQuery...

    $('.myclass').do().crazy().things();


})(jQuery);
 //  ^=======immediately invoked, and passed the jQuery object


 // out here, $ is undisturbed
alert( $ ); // "some value we don't care about"
like image 165
RightSaidFred Avatar answered Sep 19 '22 19:09

RightSaidFred