Dollar sign before self declaring anonymous function in JavaScript?

前端 未结 5 1525
闹比i
闹比i 2020-11-29 03:08

What is the difference between these two:

$(function () {
    // do stuff
});

AND

(function () {
    // do stuff
})();
         


        
5条回答
  •  盖世英雄少女心
    2020-11-29 03:23

    They are both anonymous functions, but (function(){})() is called immediately, and $(function(){}) is called when the document is ready.

    jQuery works something like this.

    window.jQuery = window.$ = function(arg) {
        if (typeof arg == 'function') {
            // call arg() when document is ready
        } else {
           // do other magics
        }
    }
    

    So you're just calling the jQuery function and passing in a function, which will be called on document ready.

    The 'Self-executing anonymous function' is the same as doing this.

    function a(){
        // do stuff
    }
    a();
    

    The only difference is that you are not polluting the global namespace.

提交回复
热议问题