简体   繁体   English

在JavaScript中自我声明匿名函数之前的美元符号?

[英]Dollar sign before self declaring anonymous function in JavaScript?

What is the difference between these two: 这两者有什么区别:

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

AND

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

The first uses jQuery to bind a function to the document.ready event. 第一个使用jQuery将函数绑定到document.ready事件。 The second declares and immediately executes a function. 第二个声明并立即执行一个函数。

$(function() {}); is a jQuery shortcut for 是一个jQuery快捷方式

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

While (function() {})(); while (function() {})(); is a instantly invoked function expression, or IIFE. 是一个即时调用的函数表达式,或IIFE。 This means that its an expression (not a statement) and it is invoked instantly after it is created. 这意味着它是一个表达式(不是语句),它在创建后立即被调用。

一个是jquery $(document).ready函数,另一个是调用自身的匿名函数。

They are both anonymous functions, but (function(){})() is called immediately, and $(function(){}) is called when the document is ready. 它们都是匿名函数,但是(function(){})()立即被调用,并且在文档准备好时调用$(function(){})

jQuery works something like this. jQuery的工作方式与此类似。

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. 所以你只是调用jQuery函数并传入一个函数,该函数将在文档就绪时调用。

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. 唯一的区别是您没有污染全局命名空间。

$(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. 一旦文件准备就绪,这个函数执行意味着整个HTML应该在执行之前加载,但在第二种情况下,函数在创建后立即调用。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM