(function(){在Javascript中的含义

Bar*_*ney 0 javascript jquery document-ready deferred-execution

我想了解这段代码之间的区别:

(function() {
Run Code Online (Sandbox Code Playgroud)

而这段代码:

$(function() {
Run Code Online (Sandbox Code Playgroud)

第一个示例是否在文档就绪后运行代码,第二个示例是什么?或者仅仅是功能的范围,仅此而已?

Dan*_*nte 5

第一个例子是一个闭包,它是JavaScript中常用的设计模式.在第二个中,你调用$函数给另一个函数作为参数(jQuery将在文档准备好后立即执行它,因为它是别名$(document).ready(function () {})).

这是关闭的一个例子:

(function () {
    var foo = 'foo';
    var bar = 'bar';
    window.foo = foo;
})();    // Those () mean that you're calling this anonymous function

console.log(typeof foo);    // Logs 'string'
console.log(typeof bar);    // Logs 'undefined', since 'bar' is internal to the closure's
                            // scope and was not exposed like was 'foo'
Run Code Online (Sandbox Code Playgroud)

这是一个例子$(function () {}):

$(function () {
    alert('Document ready');
});
Run Code Online (Sandbox Code Playgroud)

检查这些页面: