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!
Related
I see some self executing function, where the global variable is passed as an argument, even though the global variables are accessible inside the function.
var MyApp = {};
(function(app) {
//Do something with app varaible.
})(MyApp);
is there any reason to pass them to the functions through arguments?
Function arguments, as well as variables declared with var inside the scope of the function, are scoped locally and shadow any values for the same variable in outer scopes.
In your example, this allows $ to have a value outside of the function, and it is only temporarily switched to the jQuery object while inside the function.
$ = "stuff";
console.log($); // "stuff"
(function($) {
console.log($); // the jQuery object
})(jQuery);
console.log($); // "stuff"
Considering your initial code with jQuery:
Is just to help writing code, some programmers get addicted to the $ so they pass the jQuery as arguments and call it $. That code is a better way of doing this $=jQuery, in codes where other frameworks already user $, $=jQuery would overwrite other API code... You typically see that kind of code construct when you use jQuery along with other conflicting libraries that forced you to call jQuery.noConflict().
jQuery.noConflict() removes you the $ functions where you previously were able to do this $('div')... so to keep using $ as before, in code where you know that $ should mean jQuery then you declare code like:
(function($){
...
})(jQuery);
About the closures in general:
This is useful in other cases, imagine you have huge function working using the jquery $ variable and then you add a library to your project that conflicts with $, the closure above would help you in not re-write the code, you could wrap it inside the closure an user $ inside.
Just one more thing, for clearness, (function(){})() is called a closure because you declare an anonymous function an then you execute it, which means you create a private context inside that function.
link about closures: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Closures
The why for passing globals as parameter to closures, is because when you pass the globals as parameters to locals you rename that global to another name inside of the closures context only. This is a controlled way of saying "hey here jQuery is called $ and jQuery".
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 was reading this article about the module Javascript pattern, but I don't understand what is the benefit of the "Global import".
What is the difference between:
(function () {
alert($('#theForm').attr('method'));
} ());
and
(function ($) {
alert($('#theForm').attr('method'));
} (jQuery));
Both methods has the same effect, so I think I am missing the point here.
What is the point of pass global variables as parameters in the anonymous closure? what are the benefits?
Lots of scripts (such as Prototype and Mootools) also use the $ character. It is therefore sometimes useful to not use that character on a global level. You can do this in jQuery by using jQuery.noConflict(). You then have to use jQuery to do jQuery selections and the like.
If, however, you have a section of code (a "module", perhaps) that you know will only use jQuery, you can redefine $ for that section of code only using that pattern. The object known as jQuery outside the function is now known as $ inside the function:
(function($) { // the first parameter is known as $
// inside the function, you can access jQuery by the name $
}(jQuery)); // pass jQuery as the first argument
By the second version, you are ensuring that you may use the dollar-sign $ for jquery. Otherwise, you could get into trouble, when you import a second javascript library that also uses the dollar sign as an alias (prototype for example).
So by the second version, you always ensure there will be no conflicts, by passing in the unique name (jQuery in this case).
A simplified example to explain this would be as follows.
var jqueryCloneLibrary = {libName : 'jqClone_1.1.1',size : '4kb'}; //
(function(_){console.log(_.libName,_.size)}(jqueryCloneLibrary))
Above, a clone on global level has been declared and stored as a reference in var jqueryCloneLibrary.
The reference to the object i.e jqueryCloneLibrary is passed as an argument to the IIFE (immediately invoked function)
Inside the function definition, we have the parameter defined as an _ using which we are able to access the properties _.name and _.size.
We include jquery or any other library the similar way and this is known as a Global Import.
Is this jQuery code
(function(jQuery){
})(jQuery);
equivalent to
$(document).ready(function () {
});
If yes, what are the differences between the two? If not, what does the first do?
EDIT:
Thanks everybody. Most response are similar with different flavours and sample
They are not equivalent.
Your first example is an Immediately-Invoked Function Expression (IIFE). It creates a closure around locally defined variables.
Your second example specifies a function to execute when the DOM is fully loaded. It is used to ensure that all element nodes in the DOM are available before executing the enclosed code. This is also a closure.
Both examples use anonymous functions.
It is worth pointing out that it is good practice to use both of your examples, like so:
(function($){
// locally-scoped, DOM-is-NOT-Ready-code here.
$(function () {
// your locally-scoped, DOM-is-ready-code here.
});
}(jQuery)); // note that I've moved the invocation into the parens
// that contain the function. This makes JSLint happy!
Absolutely not, the first one is a self-executing anonymous function and the second is the ready handler.
(function(jQuery){
//jQuery in this scope is referencing whatever is passed-in
})(jQuery);
So, the jQuery inside of the function isn't necessarily the same jQuery outside the function. But you typically do not want to mix-n-match global variable names with local ones.
Take this example:
(function(obj) {
alert(obj);
})('Hello');
This defines a function, then immediately invokes it, passing in "Hello"
$(document).ready(function () {
});
is equivalent to this:
$(function() {
});
The first snippet is an immediately invoked anonymous function which creates a local scope:
(function() {
var x = 2;
})();
alert(x); // undefined
No. The first one isn't really doing much. Just separating any variables inside from the surrounding scope, and creating a local jQuery variable inside.
The second one passes a function that is run after the DOM is ready (in other words after the <body> has loaded).
A common equivalent to:
$(document).ready(function () {
});
is:
$(function () {
});
which does the same thing.
While this:
(function(jQuery){
})(jQuery);
is often written as:
(function($){
})(jQuery);
so that the $ variable is no longer a global variable. Useful if the global $ variable is already in use.
Not at all. The first one is a closure - a function that you create and then immediately call. However, typically you would combine the two like this:
(function($) {
// use the $ variable
$(document).ready(function(){
// ...
});
})(jQuery);
By creating the closure you are renaming "jQuery" to "$" just locally for that block of code. The reason why you use the closure syntax is so that you can use the $ variable even though it might not be defined as a jQuery object in the global scope (i.e. some JavaScript frameworks like prototype use $ as a variable).
Whenever you write a jQuery plugin you should enclose all jQuery code in this kind of closure so it doesn't interfere with any other JavaScript frameworks. If you aren't writing plugins and you don't use any other JavaScript frameworks you probably don't have to bother enclosing your code in a closure.
I'm hoping someone can explain the following usage of JavaScript.
I have a page with a script that looks like this:
(function($){
// code
// and stuff
})(jQuery);
I'm trying to understand what this code does, specifically:
The opening parenthesis at the start
The usage of the $ symbol
The jQuery in parentheses at the end
thanks!
This is an anonymous function.
The specific example you provide is usually used when jQuery (which uses the "$") is conflicting with another library (prototype also uses "$").
What this does is say that whenever "$" is used within the function, it is to reference the jQuery object.
Normal:
$("foo").doStuff()
Conflict avoidance:
jQuery("foo").doStuff()
Using anonymous function to avoid conflict:
(function($){
$("foo").doStuff();
})(jQuery)
At the highest level, it is declaring a function and invoking it in the same statement.
Let's break it down into component parts:
First, we can use $ as an argument/variable name in a function, just like anything else:
function foo($)
{
alert($);
}
foo('hi'); //alerts 'hi'
Second, we can assign a function to a variable:
var foo = function($) {
alert($);
}
foo('hi'); //alerts 'hi'
Finally, we don't have to give functions names - we can just declare them. We wrap them in parenthesis to encapsulate the entire function declaration as a var, which we then call (just like above):
(function($) {
alert($);
})('hi');
In your case, jQuery is some object being passed into the function as the $ parameter. Probably the jQuery library root object, so you can call functions on it.
The parenthesis wrap the anonymous function so it can be called right away with the parameter being a reference to jQuery
$ is a valid variable name in JavaScript, so many frameworks use it for brevity. By including it here as the function argument, you're saying that you want to use $ as an alias for jQuery. This lets you keep your code as short as possible and save your user's bandwidth.
Answered in the first part - you're sending a reference to the jQuery object/framework to your anonymous function.
Briefly:
This declares an anonymous function which accepts one argument, referred to by the local variable name of $, and then immediately calls the function passing as the first argument the jQuery object.
Less briefly:
In javascript a function is declared like this:
function foo(arg1, arg2){
}
Later the function foo can be called:
foo("arg 1", "arg 2");
But in javascript functions are first class citizens; you may, if you choose, store a function in a variable. When doing this the variable name is the function name, so you write it like this:
var foo = function(arg1, arg2){
};
The trailing semicolon is required because a variable declaration (and assignment) is a statement. Later, the function foo can be called:
foo("arg 1", "arg 2");
The advantage here is that you can pass the function to another function, or store it in an array, or whatever. Functions of this sort are called anonymous functions (because they have no function name as such).
Inside the anonymous function foo, as seen above, you can declare local variables which remain withing the scope of that function and do not exist in the scope in which the function was declared. For example, the local arg1 and arg2 variables don't exist in the scope of the variable foo (but they do exist within the anonymous function stored in foo).
This trick allows us to create a private block in which we control what things are named without worrying about stomping over someone else's namespace.
You could write the example you provided as follows:
var foo = function($){
};
fn(jQuery);
Which is the same thing, but has that ugly intermediate variable. What may not be obvious is that the declaration of the anonymous function "returns" a function reference which can be invoked later... or at the same time, merely by adding the function call syntax of ().
What the code is doing is defining an anonymous function, which creates a private scope, and then immediately calling it without storing in a variable. Like this:
function(arg1){
}("arg 1");
I am not entirely sure why there's an extra set of parentheses arroudn the anonymous function definition, but they at least make the code a little more readable/logical. You are merely passing an argument to the result of the parenthetical expression, which happens to be a function:
(function(arg1){
})("arg 1");
All of tis allows jQuery to have a globally-scoped variable named jQuery, but also allows you the user to use the shorthand of $ without conflicting with other javascript frameworks which use the same name for other things.
Let’s first look at the inner function declaration:
function($){
// code
// and stuff
}
This is an anonymouse function declaration with one parameter named $. That function is then wrapped in parenthesis and called by appending (jQuery) to it with jQuery as parameter.