用 $(function 等) 启动 javascript 代码
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12008843/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
start javascript code with $(function, etc
提问by Michael
I am studying Backbone and the todo example apps from http://todomvc.com/I have noticed there are 3 severals ways of starting the code in the files:
我正在研究来自http://todomvc.com/ 的Backbone 和 todo 示例应用程序 我注意到有 3 种方法可以在文件中启动代码:
$(function() {
// code here
});
$(function( $ ) {
// code here
});
(function() {
// code here
}());
I do not understand the differences and when I should use one over the other.
我不明白这些差异以及何时应该使用一个而不是另一个。
I also saw some people using this to start their code:
我还看到一些人使用它来启动他们的代码:
$(document).ready(function(){
// code here
});
From what I have seen, this is the full way of writing it right?
据我所见,这是完整的写法吗?
In a more general way, should I always include my javascript code into something like that in each files?
以更一般的方式,我是否应该始终将我的 javascript 代码包含在每个文件中的类似内容中?
Thanks for your advice.
谢谢你的建议。
回答by Joseph Silber
$(document).ready(function(){})
ensures that your code runs on DOM ready, so that you have access to the DOM. You can read more about this in jQuery's documentation.$(function(){})
is just an alias to #1. Any code in here will wait for DOM ready (see the docs).$(function($){})
is equivalent to #1 and #2, only you get a clean reference to jQuery in the local scope(see the note below). You can likewise pass in$
to the function in #1, and it'll do the same thing (create a local reference to jQuery).(function(){}())
is just a self-executing-anonymous-function, used to create a new closure.
$(document).ready(function(){})
确保您的代码在 DOM 上运行就绪,以便您可以访问 DOM。您可以在jQuery 的文档 中阅读有关此内容的更多信息。$(function(){})
只是#1 的别名。此处的任何代码都将等待 DOM 就绪(请参阅文档)。$(function($){})
等价于#1 和#2,只有你在本地范围内获得了对jQuery 的干净引用(参见下面的注释)。您同样可以传入$
#1 中的函数,它会做同样的事情(创建对 jQuery 的本地引用)。(function(){}())
只是一个自执行匿名函数,用于创建一个新的闭包。
Please note that none of these are specific to Backbone. The first 3 are specific to jQuery, while #4 is just vanilla JavaScript.
请注意,这些都不是专门针对 Backbone 的。前 3 个特定于 jQuery,而 #4 只是普通的 JavaScript。
Note:To understand what's going on in #3 above, remember that $
is an alias to jQuery
. However, jQuery is not the only library that uses the $
variable. Since the $
might be overwritten by someone else, you want to ensure that within your scope, $
will always reference jQuery - hence the $
argument.
注意:要了解上面#3 中发生的事情,请记住这$
是jQuery
. 但是,jQuery 并不是唯一使用该$
变量的库。由于$
可能被其他人覆盖,您希望确保在您的范围内,$
将始终引用 jQuery - 因此是$
参数。
In the end, it basically boils down to the following 2 options:
最后,它基本上归结为以下两个选项:
If your JavaScript is loaded in the
head
, you have to wait for document ready, so use this:jQuery(function($) { // Your code goes here. // Use the $ in peace... });
If you load your JavaScript at the bottom of your document (before the closing body tag - which you should definitely be doing), then there's no need to wait for document ready (since the DOM is already constructed by the time the parser gets to your script), and a SEAF(A.K.A. IIFE) will suffice:
(function($) { // Use the $ in peace... }(jQuery));
如果你的 JavaScript 被加载到 中
head
,你必须等待文档准备好,所以使用这个:jQuery(function($) { // Your code goes here. // Use the $ in peace... });
如果您在文档底部加载 JavaScript(在结束正文标记之前 -您肯定应该这样做),则无需等待文档准备就绪(因为在解析器到达您的脚本),一个SEAF(AKA IIFE)就足够了:
(function($) { // Use the $ in peace... }(jQuery));
P.S.For a good understanding of Closures and Scope, see JS101: A Brief Lesson on Scope.
PS要更好地理解闭包和作用域,请参阅JS101: A Brief Lesson on Scope。
回答by Mark Pieszak - Trilon.io
I guess it makes sense to start out, by realizing that $ = jQuery
. The purpose of which down below when reading about namespaces within anonymous functions will make more sense. But in essence, you can use either of them. One would use jQuery()
instead of $()
if they were using multiple libraries, and wanted the $
to be used by the other one.
我想通过意识到这一点开始是有意义的$ = 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()
Putting the $
within the parenthesis ensures the jQuery $ alias(you can be safe it always signifies jQuery this way).
将 放在$
括号内可确保jQuery $ 别名(您可以安全地始终以这种方式表示 jQuery)。
$(function ($) { /* code here : $ always means jQuery now */ });
Lastly you have an IIFE (Immidiately-Invoked Function Expression)- IIFE explanation
最后你有一个IIFE(立即调用的函数表达式)- IIFE 解释
(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));
The $ at the top (with it's matching jQuery on the bottom) signify that the $ (dollar sign) stands for jQuery within the scope of the namepsace. This is done to ensure that other libraries do not collide with what the developer intends/wants the $ to be used with.
顶部的 $(与底部匹配的 jQuery)表示 $(美元符号)代表名称空间范围内的 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
Now if we're outside of the namespace, we can see how these internal/public methods and variables are effected:
现在,如果我们在namespace 之外,我们可以看到这些内部/公共方法和变量是如何影响的:
// 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());
?
回答by Jamiec
These two:
这两个:
$(function() {
// code here
});
$(document).ready(function(){
// code here
});
Are directly equivalent, they are both the way to start some jQuery when the document has loaded. The former is just a shorter version of the latter.
是直接等价的,它们都是在文档加载时启动一些 jQuery 的方式。前者只是后者的较短版本。
This one:
这个:
(function() {
// code here
}());
is just a scoped function with zero parameters, which is immediately called with zero parameters.
只是一个具有零参数的作用域函数,它立即被零参数调用。