What is this unknown JavaScript syntax? - javascript

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.

Related

Can someone explain what function($) does in jQuery

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 want to know about this javascript function pattern [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
What does this “(function(){});”, a function inside brackets, mean in javascript?
javascript anonymous function
(function())()
this is used in many js library like jquery,YUi
Thats called Module Pattern. The idea is to have an encapsulated module, that cannot conflict with any other modules you or someone else has created. You can create public and private methods within that module.
See: Js Pattern
I'm not sure what (function())() means, but I'll work on the assumption that you meant (function() { … })(). It is roughly the same as:
f = function() { … }; // Define a function.
f(); // Call it.
The only difference is that it does so without requiring a variable.
It is an anonymous self executing function. It is anonymous, because it is not named, and self executing, so it runs (there would be no other way to run an un-named function).
It is particularly useful to enclose a discreet module of code, because it acts as a closure preventing variables leaking into the global namespace.
You're immediately calling an anonymus function with a specific parameter.
An example:
(function(name){ alert(name); })('peter') This alerts "peter".
In the case of jQuery you might pass jQuery as a parameter and use $ in your function. So you can still use jQuery in noConflict-mode but use the handy $:
jQuery.noConflict() (function($){ var obj = $('<div/>', { id: 'someId' }); })(jQuery)
It simply executes the code wrapped in parentheses right away (the first block returns a function, the second pair of parens executes it).
Take for instance these two snippets:
function foo() {
print 'foo';
}
(function() {
print 'foo';
})();
The first won't do anything until you call foo(); whereas the second will print 'foo' right away.

Using Self Calling Anonymous Functions and $(document).ready

I just recently learned about self calling anonymous functions. Some snippets of code that I came across used the self calling function along with the $(document).ready. It seems redundant, or pointless, to use both.
Is there a case where you'd use
(function(){
$(document).ready();
})();
vs.
$(document).ready(function(){
(function(){})();
});
I figure that you'd either want the script to be executed right away or after the DOM loaded. I can't see why you'd use both together.
Thanks.
There's definitely a use case for the first example. If you have other JS libraries/scripts loaded on the same page, there's no guarantee that they aren't overwriting the $ variable. (This is very common when you have Prototype and jQuery on the same page).
So if Prototype is using $, you would need to use jQuery anytime you wanted to work with jQuery. This can get quite ugly:
jQuery(function(){
jQuery('a', '#content').bind('click', function(){
if(jQuery(this).attr('href') == 'www.google.com')
{
alert("This link goes to Google");
jQuery(this).addClass('clicked'));
}
});
})
Remember, we can't use $ because that is a method from Prototype in the global scope.
But if you wrapped it inside of this..
(function($){
$(function(){
// your code here
});
})(jQuery);
The $ would actually reference the jQuery library inside while still referring to Prototype on the outside! This can help tidy up your code:
(function($){
$(function{}(
jQuery('a', '#content').bind('click', function(){
if(jQuery(this).attr('href') == 'www.google.com')
{
alert("This link goes to Google");
jQuery(this).addClass('clicked'));
}
});
));
})(jQuery);
This is a common pattern with jQuery extensions to ensure that they are always added to the jQuery object, but can be written using $ to keep the code tidy.
You wouldn't want to use both together, is there something you're doing that requires you to?
In the jquery api documentation here, http://api.jquery.com/ready/, you can see these examples:
The .ready() method is typically used with an anonymous function:
$(document).ready(function() {
// Handler for .ready() called.
});
Which is equivalent to calling:
$(function() {
// Handler for .ready() called.
});
But I'm not sure if this answers your question because I don't see where you actually ask one. Hope this helps just the same!
The only reason you would introduce another closure is to introduce another scope boundary for loading / protecting global objects such as $.
For Example:
$(document).ready(function(){
// Do upper scope things.
(function(){
// Do lower scope things.
})();
});
Based on you saying you have recently learning about this stuff I assume you are relativly new to JavaScript.
I have put together a blog post that might help explaining some of the basic concepts form the point of view of a newcomer to JavaScript, including function scope. http://bit.ly/tLkykX

2 ways of writing jquery, what's the difference?

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)

JavaScript: Why the anonymous function wrapper? [duplicate]

(function() {})() and its jQuery-specific cousin (function($) {})(jQuery) pop up all the time in Javascript code.
How do these constructs work, and what problems do they solve?
Examples appreciated
With the increasing popularity of JavaScript frameworks, the $ sign was used in many different occasions. So, to alleviate possible clashes, you can use those constructs:
(function ($){
// Your code using $ here.
})(jQuery);
Specifically, that's an anonymous function declaration which gets executed immediately passing the main jQuery object as parameter. Inside that function, you can use $ to refer to that object, without worrying about other frameworks being in scope as well.
This is a technique used to limit variable scope; it's the only way to prevent variables from polluting the global namespace.
var bar = 1; // bar is now part of the global namespace
alert(bar);
(function () {
var foo = 1; // foo has function scope
alert(foo);
// code to be executed goes here
})();
1) It defines an anonymous function and executes it straight away.
2) It's usually done so as not to pollute the global namespace with unwanted code.
3) You need to expose some methods from it, anything declared inside will be "private", for example:
MyLib = (function(){
// other private stuff here
return {
init: function(){
}
};
})();
Or, alternatively:
MyLib = {};
(function({
MyLib.foo = function(){
}
}));
The point is, there are many ways you can use it, but the result stays the same.
It's just an anonymous function that is called immediately. You could first create the function and then call it, and you get the same effect:
(function(){ ... })();
works as:
temp = function(){ ... };
temp();
You can also do the same with a named function:
function temp() { ... }
temp();
The code that you call jQuery-specific is only that in the sense that you use the jQuery object in it. It's just an anonymous function with a parameter, that is called immediately.
You can do the same thing in two steps, and you can do it with any parameters you like:
temp = function(answer){ ... };
temp(42);
The problem that this solves is that it creates a closuse for the code in the function. You can declare variables in it without polluting the global namespace, thus reducing the risk of conflicts when using one script along with another.
In the specific case for jQuery you use it in compatibility mode where it doesn't declare the name $ as an alias for jQuery. By sending in the jQuery object into the closure and naming the parameter $ you can still use the same syntax as without compatibility mode.
It explains here that your first construct provides scope for variables.
Variables are scoped at the function level in javascript. This is different to what you might be used to in a language like C# or Java where the variables are scoped to the block. What this means is if you declare a variable inside a loop or an if statement, it will be available to the entire function.
If you ever find yourself needing to explicitly scope a variable inside a function you can use an anonymous function to do this. You can actually create an anonymous function and then execute it straight away and all the variables inside will be scoped to the anonymous function:
(function() {
var myProperty = "hello world";
alert(myProperty);
})();
alert(typeof(myProperty)); // undefined
Another reason to do this is to remove any confusion over which framework's $ operator you are using. To force jQuery, for instance, you can do:
;(function($){
... your jQuery code here...
})(jQuery);
By passing in the $ operator as a parameter and invoking it on jQuery, the $ operator within the function is locked to jQuery even if you have other frameworks loaded.
Another use for this construct is to "capture" the values of local variables that will be used in a closure. For example:
for (var i = 0; i < 3; i++) {
$("#button"+i).click(function() {
alert(i);
});
}
The above code will make all three buttons pop up "3". On the other hand:
for (var i = 0; i < 3; i++) {
(function(i) {
$("#button"+i).click(function() {
alert(i);
});
})(i);
}
This will make the three buttons pop up "0", "1", and "2" as expected.
The reason for this is that a closure keeps a reference to its enclosing stack frame, which holds the current values of its variables. If those variables change before the closure executes, then the closure will see only the latest values, not the values as they were at the time the closure was created. By wrapping the closure creation inside another function as in the second example above, the current value of the variable i is saved in the stack frame of the anonymous function.
This is considered a closure. It means the code contained will run within its own lexical scope. This means you can define new variables and functions and they won't collide with the namespace used in code outside of the closure.
var i = 0;
alert("The magic number is " + i);
(function() {
var i = 99;
alert("The magic number inside the closure is " + i);
})();
alert("The magic number is still " + i);
This will generate three popups, demonstrating that the i in the closure does not alter the pre-existing variable of the same name:
The magic number is 0
The magic number inside the closure is 99
The magic number is still 0
They are often used in jQuery plugins. As explained in the jQuery Plugins Authoring Guide all variables declared inside { } are private and are not visible to the outside which allows for better encapsulation.
As others have said, they both define anonymous functions that are invoked immediately. I generally wrap my JavaScript class declarations in this structure in order to create a static private scope for the class. I can then place constant data, static methods, event handlers, or anything else in that scope and it will only be visible to instances of the class:
// Declare a namespace object.
window.MyLibrary = {};
// Wrap class declaration to create a private static scope.
(function() {
var incrementingID = 0;
function somePrivateStaticMethod() {
// ...
}
// Declare the MyObject class under the MyLibrary namespace.
MyLibrary.MyObject = function() {
this.id = incrementingID++;
};
// ...MyObject's prototype declaration goes here, etc...
MyLibrary.MyObject.prototype = {
memberMethod: function() {
// Do some stuff
// Maybe call a static private method!
somePrivateStaticMethod();
}
};
})();
In this example, the MyObject class is assigned to the MyLibrary namespace, so it is accessible. incrementingID and somePrivateStaticMethod() are not directly accessible outside of the anonymous function scope.
That is basically to namespace your JavaScript code.
For example, you can place any variables or functions within there, and from the outside, they don't exist in that scope. So when you encapsulate everything in there, you don't have to worry about clashes.
The () at the end means to self invoke. You can also add an argument there that will become the argument of your anonymous function. I do this with jQuery often, and you can see why...
(function($) {
// Now I can use $, but it won't affect any other library like Prototype
})(jQuery);
Evan Trimboli covers the rest in his answer.
It's a self-invoking function. Kind of like shorthand for writing
function DoSomeStuff($)
{
}
DoSomeStuff(jQuery);
What the above code is doing is creating an anonymous function on line 1, and then calling it on line 3 with 0 arguments. This effectively encapsulates all functions and variables defined within that library, because all of the functions will be accessible only inside that anonymous function.
This is good practice, and the reasoning behind it is to avoid polluting the global namespace with variables and functions, which could be clobbered by other pieces of Javascript throughout the site.
To clarify how the function is called, consider the simple example:
If you have this single line of Javascript included, it will invoke automatically without explicitly calling it:
alert('hello');
So, take that idea, and apply it to this example:
(function() {
alert('hello')
//anything I define in here is scoped to this function only
}) (); //here, the anonymous function is invoked
The end result is similar, because the anonymous function is invoked just like the previous example.
Because the good code answers are already taken :) I'll throw in a suggestion to watch some John Resig videos video 1 , video 2 (inventor of jQuery & master at JavaScript).
Some really good insights and answers provided in the videos.
That is what I happened to be doing at the moment when I saw your question.
function(){ // some code here }
is the way to define an anonymous function in javascript. They can give you the ability to execute a function in the context of another function (where you might not have that ability otherwise).

Categories