Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery $(function() {}) vs (function () {})($) [duplicate]

I understand that the following is shorthand for $( document ).ready():

$(function() {
    console.log( "ready!" );
});

I also understand what an anonymous JS function is, but does jQuery does anything special when it's called using one. I.e.:

(function() {
    console.log( "ready!" );
})($);

Is the latter just a normal anonymous JS function that uses jQuery (ie. it will NOT be considered shorthand for $(document).ready() and so will execute immediately)?

I feel this MUST have been asked before, but I can't find it if it has.

like image 590
Chuck Le Butt Avatar asked Jan 23 '17 15:01

Chuck Le Butt


People also ask

What is difference between $( document .ready function () vs $( function ()?

The key difference between $(document). ready() and $(window). load() event is that the code included inside onload function will run once the entire page(images, iframes, stylesheets,etc) are loaded whereas the $(document). ready() event fires before all images,iframes etc.

What is $( function () in jQuery?

So a jQuery function, which is prefixed with the $ or the word jQuery generally is called from within that method. $(document). ready(function() { // Assign all list items on the page to be the color red.

How do you repeat a function in jQuery?

Use the callback function parameter.

What is the use of extend in jQuery?

This extend() Method in jQuery is used to merge the contents of two or more objects together into the first object. Parameters: The extend() method accepts four parameter that is mentioned above and described below: deep: This parameter is the merge becomes recursive . target: This parameter is the object to extend.


1 Answers

As you mentioned, the former is indeed a shorthand for $(document).ready(). As for the latter, this is just an Immediately Invoked Function Expression.

(function ($) {
    console.log('ready');
})(jQuery);

This function is simply an anonymous function which receives a parameter named $. The function is immediately invoked with some value (in this case jQuery) as the parameter.

IIFEs can also be used to isolate scopes and to avoid global variables in web applications which contain multiple JavaScript files. In this case a parameterless IIFE could be used:

(function () {
    // x is only accessible within this IIFE
    var x;
    // do something...
})();

For more information regarding Immediately Invoked Function Expression, see this question: What is the purpose of a self executing function in javascript?

like image 151
Lior Erez Avatar answered Sep 21 '22 17:09

Lior Erez