Dollar sign before self declaring anonymous function in JavaScript?

こ雲淡風輕ζ 提交于 2019-11-26 09:28:54

问题


What is the difference between these two:

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

AND

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

回答1:


The first uses jQuery to bind a function to the document.ready event. The second declares and immediately executes a function.




回答2:


$(function() {}); is a jQuery shortcut for

 $(document).ready(function() { 
     /* Handler for .ready() called. */ 
 });

While (function() {})(); is a instantly invoked function expression, or IIFE. This means that its an expression (not a statement) and it is invoked instantly after it is created.




回答3:


one is a jquery $(document).ready function and the other is just an anonymous function that calls itself.




回答4:


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.




回答5:


$(function () {
    // It will invoked after document is ready
});

This function execution once documents get ready mean, the whole HTML should get loaded before its execution but in the second case, the function invoked instantly after it is created.

(function () {
    // It will invoked instantly after it is created
})();


来源:https://stackoverflow.com/questions/7614574/dollar-sign-before-self-declaring-anonymous-function-in-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!