Supongo que tiene sentido comenzar, al darse cuenta de que $ = jQuery
. El propósito de lo siguiente cuando lee sobre espacios de nombres dentro de funciones anónimas tendrá más sentido. Pero, en esencia, puedes usar cualquiera de ellos. Se usaría jQuery()
en lugar de $()
si usaban varias bibliotecas, y quería que el $
fuera utilizado por el otro.
$(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()
Poner el $
dentro del paréntesis asegura la jQuery $ alias (usted puede estar seguro que siempre significa jQuery esta manera).
$(function ($) { /* code here : $ always means jQuery now */ });
Por último tiene una IIFE (Se invoca immidiately-expresión de función) - 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));
El $ en la parte superior (con ella es a juego jQuery en la parte inferior) significan que el $ (signo de dólar) representa jQuery dentro del alcance de la marca de nombre. Esto se hace para garantizar que otras bibliotecas no colisionen con lo que el desarrollador pretende/quiere que se use $.
(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
Ahora bien, si estamos fuera del espacio de nombres, podemos ver cómo se realizan estos métodos públicos internos y/variables:
// 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());
El tercer ejemplo es ** no ** equivalente a los demás. – PPvG
Véase también [signo de dólar antes de auto declarando función anónima en JavaScript?] (Https://stackoverflow.com/questions/7614574/dollar-sign-before-self-declaring-anonymous-function-in-javascript] – Bergi