Self emitting function as jQuery ducument callback

What's the difference between

$(function() {
    // bind some event listeners
});

and

$(function() {
    // bind some event listeners
}());
+4
source share
4 answers
$(function() {
    // bind some event listeners
});

In the above case, the function is passed in jquery, which will be executed after the document is ready.

$(function() {
    // bind some event listeners
}());

In the above case, the return of the function is passed to jquery. Since the se3lf function is executed by itself, it will be executed immediately, and everything that the function returns will be passed to jquery, so this is not a good way, since the goal is to execute the function when the document is ready, which does not happen in this case

+2
source
$(function(){...}); OR $(document).ready(function(){ ... });

, DOM , , , ..ready() , , DOM .

(function(){ ... })();

, , , JavaScript. , DOM .

+1
$(function() {
    // bind some event listeners
});

, DOM , :

$(document).ready(function(){
  // Write code here
}); 

$(function() {
    // bind some event listeners
}());

, $() self invoking. , .

+1
$(function() { ... });

jQuery :

$(document).ready(function() { ... });

The expressed instant expression of the function (or IIFE), instead, is the expression "immediately executed", the agreement is enclosed in parentheses, but each kind of expression is executed immediately, see the following IIFE functions:

(function() {
    console.log("IIFE 1");
}());

+function() {
    console.log("IIFE 2");
}();

1-function() {
    console.log("IIFE 3");
}();

var f = 50 * function() {
    console.log("IIFE 4");
}();
Run codeHide result

Hope this was clear for now.

+1
source

Source: https://habr.com/ru/post/1674733/


All Articles