2012-08-17 23 views
26

我学习骨干,并从http://todomvc.com/ 我已经注意到了待办事项例如应用程序有3种severals中的文件启动代码的方式:

$(function() { 
// code here 
}); 

$(function($) { 
// code here 
}); 

(function() { 
// code here 
}()); 

我不了解这些差异,当我应该使用一个比其他

我也看到了用这个来开始他们的代码一些人:

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

从我所看到的,这是写它的完整方式吧?

在更普遍的方式,我就应该总是包括我的javascript代码到类似的东西在每个文件?

感谢您的建议。

+4

第三个例子是**不等同于其他人。 – PPvG 2012-08-17 15:44:19

+0

另请参见[自我声明在JavaScript中的匿名函数之前的美元符号?](https://stackoverflow.com/questions/7614574/dollar-sign-before-self-declaring-anonymous-function-in-javascript) – Bergi 2017-01-23 15:27:10

回答

53
  1. $(document).ready(function(){})确保您的代码在DOM就绪上运行,以便您可以访问DOM。您可以在jQuery's documentation中阅读更多关于此的内容。

  2. $(function(){})只是一个别名#1。此处的任何代码都将等待DOM准备就绪(see the docs)。

  3. $(function($){})相当于#1和#2,只有您在local scope(请参阅下面的注释)中获得对jQuery的干净引用。您也可以将$传递给#1中的函数,并且它会执行相同的操作(创建对jQuery的本地引用)。

  4. (function(){}())只是一个self-executing-anonymous-function,用于创建一个新的闭包。

请注意,这些都不是特定于Backbone的。前3个特定于jQuery,而#4只是香草JavaScript。


注:要了解发生了什么事在#3上面,记住$是一个别名jQuery。但是,jQuery不是唯一使用$变量的库。由于$可能被别人覆盖,要保证你的范围内,$总是引用jQuery的 - 因此$说法。


最后,它基本上可以归结为以下2个选项:

  1. 如果你的JavaScript是在head加载,你必须等待文件准备好,所以用这个:

    jQuery(function($) { 
        // Your code goes here. 
        // Use the $ in peace... 
    }); 
    
  2. 如果您在您的文档的底部(的结束标记之前 - which you should definitely be doing)加载你的JavaScript,那么就没有必要等待解决的文准备好了(因为在解析器到达你的脚本的时候DOM已经被构建了),以及一个SEAF(A.K.A. IIFE)就足够了:

    (function($) { 
        // Use the $ in peace... 
    }(jQuery)); 
    

附:为了更好地理解闭合和范围,请参阅JS101: A Brief Lesson on Scope

+1

只是为了避免自我执行 - 匿名 - 函数的混淆(以及某些方面的愤怒)并不真正执行自己..他们已经创造出这一点,但真的是[立即调用函数](http://benalman.com/news/2010/11/ immediate-invoked-function-expression /)。**和**在发布这个I之后立即*看到关于(AKA IIFE)的小脚注,所以nvm:P这很有趣,我们如何链接到同一篇文章 – rlemon 2012-08-17 20:27:03

+1

@ rlemon - 尽管我同意Cowboy(Ben Alman)** **中立调用函数表达式**是更准确的术语,**自动执行 - 匿名函数**已成为引用它们的标准方式。我们都链接到同一篇文章,因为这是** IIFE **名称的来源无论你称之为什么,文章都值得一读。它有这些函数表达式的一些很好的信息。 – 2012-08-17 20:35:47

+0

哦,我已经读过它了,只要人们知道它们是如何工作的以及为什么使用它们,我个人并不在乎我们称之为什么。我只是在做我的尽职调查,并将其链接起来:P但这一切都不是:P你已经有了:)我喜欢IIFE,因为它更准确,SEAF是一个丑陋的缩写。 – rlemon 2012-08-17 20:40:06

2

这两个:

$(function() { 
// code here 
}); 

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

直接等同,它们都启动一些jQuery的文件已加载时的方式。前者只是后者的缩短版本。

这一个:

(function() { 
// code here 
}()); 

只是零点的参数,它立即调用零个参数范围的功能。

18

我认为这是有道理的开始,通过实现$ = jQuery。在阅读匿名函数中的名称空间时,下面的目的会更有意义。但实质上,你可以使用它们中的任何一个。如果他们使用多个库,则会使用jQuery()而不是$(),并且希望另一个使用$

$(document).ready(function(){ 
    // Here we have jQuery(document) firing off the ready event 
    // which executes once the DOM has been created in 
    // order to ensure that elements you are trying to manipulate exist. 
}); 

​$(function() { 
    // Short-hand version of $(document).ready(function() { }); 
}); 

More information on Document.ready()

$括号内确保jQuery的别名$(可以是安全的它总是意味着jQuery的这种方式)。

$(function ($) { /* code here : $ always means jQuery now */ }); 

最后你有一个IIFE(Immidiately调用的函数表达式) - IIFE explanation

(function (myNameSpace, $) { 
    // This is an anonymous function - it is ran instantly 
    // Usually used for namespaces/etc 
    // This creates a scope/wrapper/closure around everything inside of it 
}(window.myNameSpace, jQuery)); 

顶部的$(与它的底部匹配的jQuery)表示该 $ (美元符号)代表namepsace范围内的jQuery。 这样做是为了确保其他库不会与开发者 打算/希望使用的$相冲突。

(function (myNameSpace, $) { 
    // Now because of all of this scope/wrapper/closure awesome... 
    // you can create -INTERNAL- variables (sort of like Private variables from other langs) 
    // this variable cannot be accessed outside the namespace unless it is returned/exposed 

    var internalVariable = '123'; // Internal 

    // Even Internal functions! 
    function privateFunction() { 
     console.log('this is private!'); 
    } 

    // -------------------------------------------------------- 
    // Public -method- of nameSpace exposing a private variable 
    // Notice we're using the myNameSpace object we exposed at the top/bottom 

    myNameSpace.nameSpaceMethod = function() { 
     privateFunction(); // we can call the private function only inside of the namespace 
     return internalVariable; // now we could get this variable 
    }; 
}(window.myNameSpace, jQuery)); // notice these mirror the above arguments in the anon function 

More information on anonymous functions

现在,如果我们命名空间之外,我们可以看到这些内部/ public方法和变量影响:

// This will come up undefined 
alert(internalVariable); 

// This will trigger a -method- of the myNameSpace namespace - and alert "123" 
// Showcasing how we access a Public method - which itself has access to the internal variable 
// and exposes it to us! 
alert(myNameSpace.nameSpaceMethod()); 
​