Need help understanding a javascript function - javascript

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.

Related

What is the use of passing global variables to functions through arguments in javascript?

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".

Meaning of statement in JS

Trying to figure out what this means in javascript.
(function(document) { ... } )(document);
It is isn't using jQuery, so is this just a javascript way of making this wait till document is ready to execute?
Thanks.
This won't wait for the document to be ready, this will execute the content of the function immediately. Putting the function definition in parenthesis makes it an expression, which returns a value being the function, making it directly executable. This pattern is called an Immediately-Invoked Function Expression (IIFE).
This is probably used in conjunction with a minifier like the Closure Compiler.
Inside the function, document is a local variable. This makes it possible for the minifier to reduce its name to a one or two character name.
Note also that all variables defined inside the function will be local : they won't leak in the global scope, which may be interesting if this is only part of the script.
This creates an anonymous function that takes a single argument, and immediately calls it passing document as the argument.
This:
function(document) { ... }
creates a function taking one paremeter.
This:
(function(document) { ... })
makes it (the code, not the function) a valid expression. See here.
This:
(function(document) { ... } )(document);
calls that function with document as a parameter.
It's a basic modularization pattern. In different environments you could've passed some other object instead of document, but nothing inside that function has to know bout it.
This is called self-executed function. It evaluates the anonymous function taking a parameter called document with that parameter passed in.

Placing arguments for anonymous functions in JavaScript

When I make an anonymous function in JavaScript like this:
(function(){
/* some code here */
})()
In which object will be this function added, and where will this function live?
Also you can see in the jQuery source code an anonymous function like this:
(function(window, undefined){
/* some code here */
})(window)
How do this function's arguments differentiate it from an anonymous, 0-arg function?
Functions in JavaScript are values. That is, a function is represented by an object, and like any other object it can be the value of a variable or participate in expressions.
Thus
(function() { ... })
is a value, just like 17 or "hello world" is a value.
When a function (as a value) appears in an expression, and it's followed by (...) with a comma-separated list of expressions between the parentheses, that's a function call.
OK, so:
(function() { ... })()
creates a function (as a value) and then invokes that function with no arguments. The function object, at least as a direct result of that code, is not stored anywhere. It essentially vanishes after the function call completes, and the overall value of that subexpression will be whatever the function returned.
Passing parameters to such a function is no different than passing parameters to any other function. In the specific example you quote, the purpose is to prevent certain kinds of anomalies caused by errant "alien" code. Your example really should read:
(function(window, undefined) {
// code
})(this);
The symbol this is a reserved word and its value is under complete control of the runtime. (Well, it's value in a local execution context is thusly controlled.) When evaluated in the global scope, the above code ensures that inside the anonymous function, the symbol "window" will be a reference to the global context. That sort of construct is also useful for code that may be used in contexts other than a browser, like Node.js for example, where the global context isn't called "window".
Both examples you gave are anonymous functions, according to the first line of the Wikipedia definition:
an anonymous function [...] is a function (or a subroutine) defined, and possibly called, without being bound to an identifier
The arguments do not make a difference with respect to anonymity. Anonymous functions can take 0, 1, 2, ... n arguments, just like non-anonymous functions (i.e. named functions).
One major advantage of anonymous functions is that they don't have to live anywhere -- they can be defined and used inline, just like other values of other types.
Adding to #Pointy's answer adding parameters to an anonymous function doesn't make any difference
(function(){
/* some code here */
})()
(function(window,undefined){
/* some code here */
})(window)
Both the functions are lost after they are called, the only difference is that inside the second function some variables or functions are being stored in window context, but the anonymous function in itself is lost after the call.
If you need to keep the reference to the function try
(window.myFunc = function(arg1, arg2, arg3) {
/* your code here*/
})(arg1, arg2, arg3)

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.

Categories