我认为这是有道理的开始,通过实现$ = 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());
第三个例子是**不等同于其他人。 – PPvG 2012-08-17 15:44:19
另请参见[自我声明在JavaScript中的匿名函数之前的美元符号?](https://stackoverflow.com/questions/7614574/dollar-sign-before-self-declaring-anonymous-function-in-javascript) – Bergi 2017-01-23 15:27:10