我想通过意识到这一点开始是有意义的$ = 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 () { });
});
有关 Document.ready() 的更多信息
将括号放在$
括号内可确保jQuery $ 别名(您可以放心,它总是以这种方式表示 jQuery)。
$(function ($) { /* code here : $ always means jQuery now */ });
最后你有一个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));
顶部的 $(与底部的 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
有关匿名函数的更多信息
现在,如果我们在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());