This question already has answers here:
What does !function ($) { $(function(){ }) }(window.jQuery) do?
(1 answer)
Why write code Jquery like this
(4 answers)
Closed 9 years ago.
I am a javascript newbie and recently came into the following code.
(function($){
if(!document.defaultView || !document.defaultView.getComputedStyle){
var oldCurCSS = jQuery.curCSS;
jQuery.curCSS = function(elem, name, force){
if(name !== 'backgroundPosition' || !elem.currentStyle || elem.currentStyle[ name ]){
return oldCurCSS.apply(this, arguments);
}
var style = elem.style;
if ( !force && style && style[ name ] ){
return style[ name ];
}
return oldCurCSS(elem, 'backgroundPositionX', force) +' '+ oldCurCSS(elem, 'backgroundPositionY', force);
};
}
})(jQuery);
What is function($) {...} (jQuery)?
PS: I also don't quite get what the code is for... If possible please give a hint on it.
It's a self-executing anonoymous function called with jQuery as argument, that gets renamed to $ inside the function signature.
Since you don't know if jQuery.noConflict() has been used in the page (especially if you are writing distributable code like Plugins), this way you can use the shorthand $ inside your function safely.
Who wrote it is actually stupid beacuse he's using jQuery inside the function anyway : )
It also prevents the variables from polluting the global namespace and encapsulates them making them unaccessible from outside the function.
That's to prevent the code from interfering with a global variable named $, so that you can use other libraries that use the $ symbol too.
Inside the function, $ will only refer to the jQuery object.
Refer http://docs.jquery.com/Plugins/Authoring
It is to make sure $ means the same thing as jQuery. Other libraries may change what $ means, so this is needed.
function($) is called with jQuery as an argument, therefore $ gets set to jQuery within the function.
That is a self executing function, think of it like document.ready function in jQuery, except that this function will fire once its loaded.
(function(){}) will declare the function, but by adding () this can be fired immediately.
You can pass parameter s to this function as well. $ is actually an alias of jQuery, so to make sure that you are using jQuery, this is passed as a parameter and aliased as $ which is the convention.
(function(myAwesomePlugin){})(jQuery);
This is also valid. You can use it like myAwesomePlugin("#id").click() ...
basically it’s an anonymous function that lets jQuery play nicely with other javascript libraries that might have $ variable/function. It is executed as soon as the DOM is parsed and is invoked in order of appearance if there are multiple appearances. At this point the document is however not displayed, its just parsed.
Apart from what has been said already, this self-executing function encapsulates all variables and other functions, so the main (window) namespace remains unpolluted as all variables and functions are 'local'.
Related
In order to prevent prototype.js conflicts with jquery I wrapped my jquery code in the following snippet:
(function($) {
})(jQuery);
If I understood this correnctly, $ === jQuery would be true inside my function. But is the actual "in parameter" jQuery in this case, which gets the alias $ inside my function?
If my assumption is correct, do I need to pass jQuery on both places in order to call it jQuery, or would it be ok to just pass it at the end of the function?
Within your IIFE you can use either $ or jQuery - they're both in scope.
Only the (jQuery) is actually being passed as an argument - the $ is just the function parameter (and therefore aliased to jQuery).
To see that, your code is almost equivalent to:
var f = function($) {
...
};
f(jQuery);
except that your IIFE is an anonymous function.
If I understood this correnctly, $ === jQuery would be true inside my function. But is the actual "in parameter" jQuery in this case, which gets the alias $ inside my function?
Yes. $ is the parameter name, and the variable jQuery is what you pass in as an argument - it could be any expression.
If my assumption is correct, do I need to pass jQuery on both places in order to call it jQuery, or would it be ok to just pass it at the end of the function?
Yes, you would need to rename the parameter. Only it doesn't make much sense then, as you could just refer to the global jQuery variable then (unless you plan to overwrite that, e.g. with a different jQuery version) - the $ alias is only for brevity. If you want to avoid confusion with Prototype, use jQ instead.
Inside the closure, only $ reliably references the jQuery library; more specifically, the library version at that point in time.
When another version of the library is loaded afterwards, only $ still points to what you expect; the jQuery symbol would have been replaced by the latter version.
If you wish to use the jQuery alias inside the function you would need to rename $ to jQuery in the function arguments.
I am using jQuery in some custom files added to a Wordpress site, and am using this to allow me to use the "$" shortcut:
jQuery(function ($) {
$(selector).bla();
// etc
}
However, if I want to split my code into several files, this construct needs to exist in each file, and then functions from one cannot be called from the other. How to do this? Can I somehow declare certain functions as global?
You might want to look at using requirejs to define modules, then pass the modules in as dependencies. You can also use it to define jQuery as as dependency so that it can be scoped locally with whatever variable name you want.
require(['jquery','somemodule','someothermodule'], function($,module1,module2) {
$(function() {
var mod1 = new module1();
var mod2 = new module2();
...
});
});
You can use something like this:
var myFunc = function($) {
function toExport() {
alert($);
}
return toExport;
}(jQuery);
Just return resources you need (it can be single function, or object, or anything you want actually.)
jQueryUI is actually written a similar way:
(function( $, undefined ) {
...
}( jQuery ) );
This way the $ is guaranteed to be a synonym for the jQuery function and the keyword undefined will be defined as parameter with an undefined value. The undefined portion actually fixes some nit picky issues with a few browsers since they don't all handle undefined the same way.
You can always declare functions outside the jQuery(function() {...}); construct, in global scope.
You just cannot access the DOM before it is ready, which means you cannot execute those functions outside jQuery(function() {...}); if they access the DOM.
You can also always create a global variable by assigning a value to window property:
window.theanswer = 42;
Adding many values to the global namespace is not a good practice, and other techniques exist to create modular JavaScript to solve this problem. See tvanfosson's answer.
Recently I was reading someone else's code, and came across this:
// Semicolon (;) to ensure closing of earlier scripting
// Encapsulation
// $ is assigned to jQuery
;(function($) {
// DOM Ready
$(function() {
...
});
})(jQuery);
I understand the point of the leading ;, And I understand that $(function() { is the same as document ready, but what is the point of adding function($)?
I understand it's a closure, but since this is always being called at the global scope, it seems like you don't need to bother with it. The $(function() { will use the same global object either way, no?
Is it to safeguard against something, or is it a best practice for another reason?
It's a common structure for a jQuery plugin. It safeguards against the $ identifier having been overwritten and used for something else. Inside the anonymous function, $ is always going to refer to jQuery.
Example:
$ = "oh no";
$(function() { //Big problem!
//DOM ready
});
By introducing a new scope, you can ensure that $ refers to what you expect it to:
$ = "oh no";
(function($) { //New scope, $ is redeclared and jQuery is assigned to it
$(function() { //No problem!
//DOM ready
});
}(jQuery));
The main reasoning behind this is that numerous other JavaScript libraries use $ as an identifier (e.g. PrototypeJS). If you wanted to use both Prototype and jQuery, you need to let Prototype have its $ identifier, but you probably don't want to write out jQuery every time you want to call a jQuery method. By introducing a new scope you allow jQuery to have its $ back in that execution context.
The code sample you've provided is an example of a Self-Invoking Function:
(function(){
// some code…
})();
The first set of parentheses defines a function: (an anonymous function wrapped in parentheses)
(function() {})
That defines the anonymous function. On its own, it doesn't do anything. But if you add a set of parentheses () after the definition, it's the same as the parentheses used to call a function.
Try this out:
(function(message) {
alert(message);
})("Hello World");
That creates a function which accepts a parameter, and displays an alert box containing the provided value. Then, it immediately calls that function with a parameter of "Hello World".
In your example, a self-invoking function is defined. It accepts a parameter, which is named $. Then, the function is immediately called, with a reference to jQuery being passed in as the argument.
This is common if you want jQuery to operate in noConflict() mode (which removes the global reference to $).
In noConflict() mode, you can still access jQuery via the jQuery global variable, but most people would rather use $, so this self-calling function accepts the global jQuery variable as a parameter named $ in the scope of the function, which leaves you free to use the $ shortcut within the self-invoking function while having jQuery operate in noConflict() mode to avoid clashes with other libraries that use $ in the global scope.
Hope this answers your question!
I have got a function, inside which are some simple expressions, adding nums, appending doms, etc.
Since I only have to call it once, so an anonymous function could do it. But which way should I choose and what's the difference?
1: Shorthand for $(document).ready() {}) I seen this a lot,
$(function(){
var something;
++something;
});
2: Found in jquery plugins. Is it binded to $(document).ready() too?
(function ($) {
var something;
++something;
})(jQuery);
The second one is not bound to the ready event.
In detail. This:
$(function(){ /* ... */ });
needs a variable $ defined. Usually this variable exists when jQuery is loaded and points to the jQuery function.
Subsequently, when you call the jQuery function with a function argument, jQuery is binding this function argument to the ready event. The above is equivalent to
jQuery(function(){ /* ... */ });
which is in turn a convenience shorthand for
jQuery(document).ready(function(){ /* ... */ });
Your second code snippet
(function ($) { /* ... */ })(jQuery);
does not rely on $ being defined or pointing to jQuery() (this can happen if multiple JS frameworks are loaded in parallel).
To still have the convenience of $ within a certain region of code, it creates a function within which $ is defined and points to jQuery(). However, it is not bound to a DOM event.
But this would be:
(function ($) {
$(function(){ /* ... */ });
})(jQuery);
This set-up is used to minimize the conflict between JS frameworks or other pieces of code that rely on $. jQuery plug-in authors use it to write plug-ins that work under many environments.
If you think the combined one is too complicated, jQuery also has a shorthand feature, which avoids variable conflicts and binds to document ready at the same time. But be careful, it only works on jQuery and has some downsides.
jQuery(function($) { /* some code that uses $ */ });
For more details, see these two articles:
Using jQuery with Other Libraries
.ready() # api.jquery.com (Aliasing the jQuery Namespace)
First
It's just shorthand
Second
You are sandboxing the use of $ to reduce conflicts with other libraries that use the $ shorthand.
$ is just a shortcut for the jQuery variable and is being passed into the inner function of the immediately invoked function...
Example
var outerVar = "something";
(function innerFunc(passedVar) {
passedVar === "something"; //true
})(outerVar);
innerFunc is executed and passed outerVar as its argument.
In your first example, the shorthand form is functionally identical to $(document).ready().
The second example is an immediately-invoked anonymous function (Thanks #Raynos for the correction: this is often called a self-invoking function; it is not one). The function is defined and executed in place, taking jQuery as its argument. One advantage of this approach is that variables declared within the function will not "pollute" the global (window) scope (as opposed, for example, to simply running that code outside the function). In your example, something is undefined outside the function.
Since jQuery is brought into the function as the argument $, $ is guaranteed to be jQuery within the body of that function -- even in cases where other libraries are using $ outside the function.
A useful side note: it's sometimes helpful to name "anonymous" functions. The, uh, functionality remains the same, but names can make it much easier to debug complex code.
(function superFunction (foo) { // naming this "superFunction"
var something = 10;
do_something_with( foo, something );
})(bar);
No it isn't, it is just a shorthand
No it isn't. This code makes sure that $ is really jQuery and not just another javascript library
From http://docs.jquery.com/Plugins/Authoring:
But wait! Where's my awesome dollar sign that I know and love? It's
still there, however to make sure that your plugin doesn't collide
with other libraries that might use the dollar sign, it's a best
practice to pass jQuery to a self executing function (closure) that
maps it to the dollar sign so it can't be overwritten by another
library in the scope of its execution.
Just combine the two styles.
jQuery(function($) {
// uses the real jQuery as $
// code
});
The first style was used to run some code when the DOM is ready.
The second style is used to ensure $ === jQuery and also to make $ a local variable (reduces lookup time by a tiny fraction)
I am reading up on creating custom jQuery plugins and am a little confused as to the meaning of the following syntax:
(function($){
$.fn.truncate = function() {
return this.each(function() {
});
};
})(jQuery);
I understand that function($) is an anonymous function that accepts the $. I just don't quite understand why this function is wrapped in brackets and how the following sets of brackets with jQuery in them...work.
The following parameters with jQuery are just executing the anonymous function and passing in jQuery as the $ parameter. This ensures that $ = jQuery just incase window.$ doesn't equal jQuery.
Here is a rewrite of the code that might make more sense:
function myFunc($) {
$.fn.truncate = function() {
return this.each(function() {
});
}
myFunc(jQuery);
The surrounding parentheses create an anonymous function to which the $ symbol references the global jQuery object.
$.fn.truncate - This means that you are extending the jQuery object to include a new function called truncate.
Usage $( '#someElement' ).truncate();
It is not safe to assume that $ is owned by the jQuery library. Some other javascript libraries/users may/do use that identifier for other purposes. However, jQuery is always the jQuery library (barring any evildoers).
This anonymous function handily and safely exposes the $ shortcut as jQuery by making it a local parameter to the anonymous function. Since parameters will override any globals only for the scope of a function this will not affect any other user/library code outside of it.
Finally, where the anonymous function is executed jQuery is passed in as the first paramter to fill $.
So when boiled down, this is just a shortcut taken by plugin developers so that they can safely and reliably use $; if you don't mind using jQuery everywhere instead then this is totally optional.