Different forms of defining a function - javascript

What is the difference between following forms of function definition:
$.myFunction = function() {
//function body
};
var myFunction = function() {
//function body
};
$(myFunction = function() {
//function body
});

First one adds a function myFunction to $ which can be any of the JavaScript libraries such as jQuery, mooTools, Prototype, etc that use $ internally.
In first function, you are simply adding your own function to javascript library designated by $.
Second one is Function Expression as oppossed to Function Declaration which has this form:
function myFunction() {
//function body
}
Third one looks weired but it is also Function Expression used in the context of a JavaScript library due to $ then whatever that library is meaning by that.
To know more about the differece between Function Expression and Function Declaration, check out this excellent post:
Named function expressions demystified
The most important differece between Function Expression and Function Declaration for you to keep in mind is that Function Declaration no matter where declared is available throughout (because they are hoisted to top) whereas Function Expression can only run if it has been defined before or up somewhere for your later code. An example would be:
foo1(); // alerts "I am function declaration"
foo2(); // error, undefined function
function foo1() {
alert('I am function declaration');
}
var foo2 = function() {
alert('I am function expression');
};
foo1(); // alerts "I am function declaration"
foo2(); // alerts "I am function expression"
FYI, there are also self-invoking anonymous functions and self-inovking named functions:
// self invoking anonymous function
(function(){
// code
})();
// self invoking named function
(function foo(){
// code
})();
And function declarations converted into function expression using those chars:
! function(){
// code
})();
+ function foo(){
// code
})();
Notice that self-invoking functions are run as soon as parsed because of () at the end of their signature.

$.myFunction = function() {
//function body
};
This creates a function as a property of the $ object. If you're using jQuery then $ is the global jQuery object. You would call this function with $.myFunction()
var myFunction = function() {
//function body
};
This creates a function assigned to a variable called myFunction. If you do this inside another function, then myFunction will only be available in that scope.
$(myFunction = function() {
//function body
});
This one is doing two things, let's break it down into two steps to make it more clear:
myFunction = function() { // step 1
//function body
};
$(myFunction); // step 2
The first step is creating a function assigned to a global variable called myFunction. The variable is global because you didn't use the var keyword. In general, you probably don't want to use a global variable, and certainly not when its definition isn't very obvious.
The second step is (assuming you're using jQuery) passing myFunction to jQuery to be executed when the DOM has finished loading. See the jQuery documentation for more information.
It's more common to pass a function to jQuery without assigning it to any variable, i.e.
$(function() {
//function body
});

Well really only one of those is what I would call a function definition, the second one. The first one is extending the global jQuery object (or any other library that uses the dollar sign) with that function and third one is just weird.

Assuming the "$" stands for jQuery (which seems quite obvious here), the third syntax defines an anonymous function and pass it as an argument to jQuery, which is a shortcut for registering a callback for jQuery.DocumentReady.

Related

javascript auto execute anonymous function - parenthesis [duplicate]

I was reading some posts about closures and saw this everywhere, but there is no clear explanation how it works - everytime I was just told to use it...:
// Create a new anonymous function, to use as a wrapper
(function(){
// The variable that would, normally, be global
var msg = "Thanks for visiting!";
// Binding a new function to a global object
window.onunload = function(){
// Which uses the 'hidden' variable
alert( msg );
};
// Close off the anonymous function and execute it
})();
Ok I see that we will create new anonymous function and then execute it. So after that this simple code should work (and it does):
(function (msg){alert(msg)})('SO');
My question is what kind of magic happens here? I thought that when I wrote:
(function (msg){alert(msg)})
then a new unnamed function would be created like function ""(msg) ...
but then why doesn't this work?
(function (msg){alert(msg)});
('SO');
Why does it need to be in the same line?
Could you please point me some posts or give me an explanation?
Drop the semicolon after the function definition.
(function (msg){alert(msg)})
('SO');
Above should work.
DEMO Page: https://jsfiddle.net/e7ooeq6m/
I have discussed this kind of pattern in this post:
jQuery and $ questions
EDIT:
If you look at ECMA script specification, there are 3 ways you can define a function. (Page 98, Section 13 Function Definition)
1. Using Function constructor
var sum = new Function('a','b', 'return a + b;');
alert(sum(10, 20)); //alerts 30
2. Using Function declaration.
function sum(a, b)
{
return a + b;
}
alert(sum(10, 10)); //Alerts 20;
3. Function Expression
var sum = function(a, b) { return a + b; }
alert(sum(5, 5)); // alerts 10
So you may ask, what's the difference between declaration and expression?
From ECMA Script specification:
FunctionDeclaration :
function Identifier ( FormalParameterListopt ){ FunctionBody
}
FunctionExpression :
function Identifieropt ( FormalParameterListopt ){ FunctionBody
}
If you notice, 'identifier' is optional for function expression. And when you don't give an identifier, you create an anonymous function. It doesn't mean that you can't specify an identifier.
This means following is valid.
var sum = function mySum(a, b) { return a + b; }
Important point to note is that you can use 'mySum' only inside the mySum function body, not outside. See following example:
var test1 = function test2() { alert(typeof test2); }
alert(typeof(test2)); //alerts 'undefined', surprise!
test1(); //alerts 'function' because test2 is a function.
Live Demo
Compare this to
function test1() { alert(typeof test1) };
alert(typeof test1); //alerts 'function'
test1(); //alerts 'function'
Armed with this knowledge, let's try to analyze your code.
When you have code like,
function(msg) { alert(msg); }
You created a function expression. And you can execute this function expression by wrapping it inside parenthesis.
(function(msg) { alert(msg); })('SO'); //alerts SO.
It's called a self-invoked function.
What you are doing when you call (function(){}) is returning a function object. When you append () to it, it is invoked and anything in the body is executed. The ; denotes the end of the statement, that's why the 2nd invocation fails.
One thing I found confusing is that the "()" are grouping operators.
Here is your basic declared function.
Ex. 1:
var message = 'SO';
function foo(msg) {
alert(msg);
}
foo(message);
Functions are objects, and can be grouped. So let's throw parens around the function.
Ex. 2:
var message = 'SO';
function foo(msg) { //declares foo
alert(msg);
}
(foo)(message); // calls foo
Now instead of declaring and right-away calling the same function, we can use basic substitution to declare it as we call it.
Ex. 3.
var message = 'SO';
(function foo(msg) {
alert(msg);
})(message); // declares & calls foo
Finally, we don't have a need for that extra foo because we're not using the name to call it! Functions can be anonymous.
Ex. 4.
var message = 'SO';
(function (msg) { // remove unnecessary reference to foo
alert(msg);
})(message);
To answer your question, refer back to Example 2. Your first line declares some nameless function and groups it, but does not call it. The second line groups a string. Both do nothing. (Vincent's first example.)
(function (msg){alert(msg)});
('SO'); // nothing.
(foo);
(msg); //Still nothing.
But
(foo)
(msg); //works
An anonymous function is not a function with the name "". It is simply a function without a name.
Like any other value in JavaScript, a function does not need a name to be created. Though it is far more useful to actually bind it to a name just like any other value.
But like any other value, you sometimes want to use it without binding it to a name. That's the self-invoking pattern.
Here is a function and a number, not bound, they do nothing and can never be used:
function(){ alert("plop"); }
2;
So we have to store them in a variable to be able to use them, just like any other value:
var f = function(){ alert("plop"); }
var n = 2;
You can also use syntatic sugar to bind the function to a variable:
function f(){ alert("plop"); }
var n = 2;
But if naming them is not required and would lead to more confusion and less readability, you could just use them right away.
(function(){ alert("plop"); })(); // will display "plop"
alert(2 + 3); // will display 5
Here, my function and my numbers are not bound to a variable, but they can still be used.
Said like this, it looks like self-invoking function have no real value. But you have to keep in mind that JavaScript scope delimiter is the function and not the block ({}).
So a self-invoking function actually has the same meaning as a C++, C# or Java block. Which means that variable created inside will not "leak" outside the scope. This is very useful in JavaScript in order not to pollute the global scope.
It's just how JavaScript works. You can declare a named function:
function foo(msg){
alert(msg);
}
And call it:
foo("Hi!");
Or, you can declare an anonymous function:
var foo = function (msg) {
alert(msg);
}
And call that:
foo("Hi!");
Or, you can just never bind the function to a name:
(function(msg){
alert(msg);
})("Hi!");
Functions can also return functions:
function make_foo() {
return function(msg){ alert(msg) };
}
(make_foo())("Hi!");
It's worth nothing that any variables defined with "var" in the body of make_foo will be closed over by each function returned by make_foo. This is a closure, and it means that the any change made to the value by one function will be visible by another.
This lets you encapsulate information, if you desire:
function make_greeter(msg){
return function() { alert(msg) };
}
var hello = make_greeter("Hello!");
hello();
It's just how nearly every programming language but Java works.
The code you show,
(function (msg){alert(msg)});
('SO');
consist of two statements. The first is an expression which yields a function object (which will then be garbage collected because it is not saved). The second is an expression which yields a string. To apply the function to the string, you either need to pass the string as an argument to the function when it is created (which you also show above), or you will need to actually store the function in a variable, so that you can apply it at a later time, at your leisure. Like so:
var f = (function (msg){alert(msg)});
f('SO');
Note that by storing an anonymous function (a lambda function) in a variable, your are effectively giving it a name. Hence you may just as well define a regular function:
function f(msg) {alert(msg)};
f('SO');
In summary of the previous comments:
function() {
alert("hello");
}();
when not assigned to a variable, yields a syntax error. The code is parsed as a function statement (or definition), which renders the closing parentheses syntactically incorrect. Adding parentheses around the function portion tells the interpreter (and programmer) that this is a function expression (or invocation), as in
(function() {
alert("hello");
})();
This is a self-invoking function, meaning it is created anonymously and runs immediately because the invocation happens in the same line where it is declared. This self-invoking function is indicated with the familiar syntax to call a no-argument function, plus added parentheses around the name of the function: (myFunction)();.
There is a good SO discussion JavaScript function syntax.
My understanding of the asker's question is such that:
How does this magic work:
(function(){}) ('input') // Used in his example
I may be wrong. However, the usual practice that people are familiar with is:
(function(){}('input') )
The reason is such that JavaScript parentheses AKA (), can't contain statements and when the parser encounters the function keyword, it knows to parse it as a function expression and not a function declaration.
Source: blog post Immediately-Invoked Function Expression (IIFE)
examples without brackets:
void function (msg) { alert(msg); }
('SO');
(this is the only real use of void, afaik)
or
var a = function (msg) { alert(msg); }
('SO');
or
!function (msg) { alert(msg); }
('SO');
work as well. the void is causing the expression to evaluate, as well as the assignment and the bang. the last one works with ~, +, -, delete, typeof, some of the unary operators (void is one as well). not working are of couse ++, -- because of the requirement of a variable.
the line break is not necessary.
This answer is not strictly related to the question, but you might be interested to find out that this kind of syntax feature is not particular to functions. For example, we can always do something like this:
alert(
{foo: "I am foo", bar: "I am bar"}.foo
); // alerts "I am foo"
Related to functions. As they are objects, which inherit from Function.prototype, we can do things like:
Function.prototype.foo = function () {
return function () {
alert("foo");
};
};
var bar = (function () {}).foo();
bar(); // alerts foo
And you know, we don't even have to surround functions with parenthesis in order to execute them. Anyway, as long as we try to assign the result to a variable.
var x = function () {} (); // this function is executed but does nothing
function () {} (); // syntax error
One other thing you may do with functions, as soon as you declare them, is to invoke the new operator over them and obtain an object. The following are equivalent:
var obj = new function () {
this.foo = "bar";
};
var obj = {
foo : "bar"
};
There is one more property JavaScript function has. If you want to call same anonymous function recursively.
(function forInternalOnly(){
//you can use forInternalOnly to call this anonymous function
/// forInternalOnly can be used inside function only, like
var result = forInternalOnly();
})();
//this will not work
forInternalOnly();// no such a method exist
It is a self-executing anonymous function. The first set of brackets contain the expressions to be executed, and the second set of brackets executes those expressions.
(function () {
return ( 10 + 20 );
})();
Peter Michaux discusses the difference in An Important Pair of Parentheses.
It is a useful construct when trying to hide variables from the parent namespace. All the code within the function is contained in the private scope of the function, meaning it can't be accessed at all from outside the function, making it truly private.
See:
Closure (computer science)
JavaScript Namespacing
Important Pair of Javascript Parentheses
Another point of view
First, you can declare an anonymous function:
var foo = function(msg){
alert(msg);
}
Then you call it:
foo ('Few');
Because foo = function(msg){alert(msg);} so you can replace foo as:
function(msg){
alert(msg);
} ('Few');
But you should wrap your entire anonymous function inside pair of braces to avoid syntax error of declaring function when parsing. Then we have,
(function(msg){
alert(msg);
}) ('Few');
By this way, It's easy understand for me.
When you did:
(function (msg){alert(msg)});
('SO');
You ended the function before ('SO') because of the semicolon. If you just write:
(function (msg){alert(msg)})
('SO');
It will work.
Working example: http://jsfiddle.net/oliverni/dbVjg/
The simple reason why it doesn't work is not because of the ; indicating the end of the anonymous function. It is because without the () on the end of a function call, it is not a function call. That is,
function help() {return true;}
If you call result = help(); this is a call to a function and will return true.
If you call result = help; this is not a call. It is an assignment where help is treated like data to be assigned to result.
What you did was declaring/instantiating an anonymous function by adding the semicolon,
(function (msg) { /* Code here */ });
and then tried to call it in another statement by using just parentheses... Obviously because the function has no name, but this will not work:
('SO');
The interpreter sees the parentheses on the second line as a new instruction/statement, and thus it does not work, even if you did it like this:
(function (msg){/*code here*/});('SO');
It still doesn't work, but it works when you remove the semicolon because the interpreter ignores white spaces and carriages and sees the complete code as one statement.
(function (msg){/*code here*/}) // This space is ignored by the interpreter
('SO');
Conclusion: a function call is not a function call without the () on the end unless under specific conditions such as being invoked by another function, that is, onload='help' would execute the help function even though the parentheses were not included. I believe setTimeout and setInterval also allow this type of function call too, and I also believe that the interpreter adds the parentheses behind the scenes anyhow which brings us back to "a function call is not a function call without the parentheses".
(function (msg){alert(msg)})
('SO');
This is a common method of using an anonymous function as a closure which many JavaScript frameworks use.
This function called is automatically when the code is compiled.
If placing ; at the first line, the compiler treated it as two different lines. So you can't get the same results as above.
This can also be written as:
(function (msg){alert(msg)}('SO'));
For more details, look into JavaScript/Anonymous Functions.
The IIFE simply compartmentalizes the function and hides the msg variable so as to not "pollute" the global namespace. In reality, just keep it simple and do like below unless you are building a billion dollar website.
var msg = "later dude";
window.onunload = function(msg){
alert( msg );
};
You could namespace your msg property using a Revealing Module Pattern like:
var myScript = (function() {
var pub = {};
//myscript.msg
pub.msg = "later dude";
window.onunload = function(msg) {
alert(msg);
};
//API
return pub;
}());
Anonymous functions are functions that are dynamically declared at
runtime. They’re called anonymous functions because they aren’t
given a name in the same way as normal functions.
Anonymous functions are declared using the function operator instead
of the function declaration. You can use the function operator to
create a new function wherever it’s valid to put an expression. For
example, you could declare a new function as a parameter to a
function call or to assign a property of another object.
Here’s a typical example of a named function:
function flyToTheMoon() {
alert("Zoom! Zoom! Zoom!");
}
flyToTheMoon();
Here’s the same example created as an anonymous function:
var flyToTheMoon = function() {
alert("Zoom! Zoom! Zoom!");
}
flyToTheMoon();
For details please read http://helephant.com/2008/08/23/javascript-anonymous-functions/
Anonymous functions are meant to be one-shot deal where you define a function on the fly so that it generates an output from you from an input that you are providing. Except that you did not provide the input. Instead, you wrote something on the second line ('SO'); - an independent statement that has nothing to do with the function. What did you expect? :)

how to use javascript functions? (defining functions in label)

There are different ways of defining the javascript functions. I often use the simplest way to define the function
function myfunc(){
}
and the next way to define the function in the variable like this (a little bit confusing the way of using)
var myvar = myfunc(){
/*some code*/
}
and the difficult way for me and mostly found in codes developed by advanced programmers like the following
var SqueezeBox={presets:{onOpen:function(){},onClose:function(){}}
Please, can anyone clear my concept on this how can I use?
function myfunc(){}
Function declaration: the function is declared using the standard syntax
function functionName(params[]) {
//functionbody
}
Using this syntax declares the function at the begin of the scope execution, so they'll be available everywhere in their scope(and in their descendeant scopes).
var s = myfunc(); //s == 0
function myfunc() {return 0;}
var myfunc = function() {};
This uses the pattern known as function expression, it just assigns a reference of an anonymous function to a variable named myfunc. Using this syntax won't allow you to use the function until the variable is parsed. Even if variables are hoisted at the top of their scope, they're initialized when the interpreter parses them, so the above example won't work:
var s = myfunc(); //ReferenceError: myfunc is not defined
var myfunc = function() {return 0;};
But the example below will:
var myfunc = function() {return 0;};
var s = myfunc(); //s == 0
The third example is just assigning an anonymous function to an object property(also known as object method) in the way we've just done with function expression, so if I use the pattern above the code will become:
var onOpen = function() {},
onClose = function() {},
SqueezeBox = {//curly braces denotes an object literal
presets: {//again, this is a nested object literal
onOpen: onOpen,
onClose: onClose
}
};
This acts exactly the same as your example, with the only difference that here I used a variable to get a reference to the anonymous function before passing it to the object. If you need to know more about objects, I recommend you reading the MDN docs. Anyway, if you're really intrested in how JS works, I'd suggest Javascript Garden, which is a very good article about JS.
The first code snippet is a function declaration:
function myfunc() { }
You are declaring a named function called myfunc. You can verify this by myfunc.name === "myfunc"
Your second code snippet contains syntax error. I believe you meant:
var myvar = function() { };
This is an anonymous function expression assigned to a variable. You can verify this by typeof myvar === "function" and myvar.name === "".
The third snippet is a javascript object. Basically you can think of it as a Map or Dictionary<string, object>. So SqueezeBox contains 1 key presets, which in turn is a dictionary that contains 2 keys, onOpen and onClose, which both of them are anonymous functions.
In
var SqueezeBox={presets:{onOpen:function(){},onClose:function(){}}}
He's creating an object SqueezeBox containing another object presets with two empty anonymous functions, he's defining the function inline with an empty body inside the {}.
A better way to see it is formatted this way:
var SqueezeBox={
presets:{
onOpen:function(){/* empty function body */},
onClose:function(){/*empty function body */}
}
}
There is a lot of useful information on this subject here
Functions can have a name, which if specified cannot be changed. Functions can also be assigned to variables like any other object in javascript.
The first example is of a function declaration:
function myfunc(){
}
Using the function declaration you will be able to call the function from anywhere within the closure in which the function is declared, even if it is declared after it is used.
The other two examples are function expressions:
var myvar = function(){
/*some code*/
}
var SqueezeBox= {
presets: {
onOpen:function(){/* empty function body */},
onClose:function(){/*empty function body */}
}
}
Using function expressions you are assigning functions to a variable. When doing this you must declare them before you use them. Most of the time you see this the functions will be anonymous but it is possible to name a function in an expression:
var myvar = function myFunc(){
myFunc(); // Because it has a name you can now call it recursively
}
When doing this, the myFunc function is only available within the body of the function because it is still a function expression rather than a declaration.
The third example declares a javascript object literal, SqueezeBox and within that object there is another called presets. Within this object there are two more objects/labels called onOpen and onClose. This means you can do the following to use these functions:
SqueezeBox.presets.onOpen();
SqueezeBox.presets.onClose();
You can think of onOpen and onClose as variables that are part of the object. So it's very similar to doing the following (but the variable is only in the scope of the presets object which is only available within the SqueezeBox object).
var onOpen = function() {};
This has already been answered here: What is the difference between a function expression vs declaration in Javascript?.
For the last example, as Atropo said, it's affecting an anonymous function to an object. It's similar to the var example.

JavaScript: What is an anonymous function? [duplicate]

I was reading some posts about closures and saw this everywhere, but there is no clear explanation how it works - everytime I was just told to use it...:
// Create a new anonymous function, to use as a wrapper
(function(){
// The variable that would, normally, be global
var msg = "Thanks for visiting!";
// Binding a new function to a global object
window.onunload = function(){
// Which uses the 'hidden' variable
alert( msg );
};
// Close off the anonymous function and execute it
})();
Ok I see that we will create new anonymous function and then execute it. So after that this simple code should work (and it does):
(function (msg){alert(msg)})('SO');
My question is what kind of magic happens here? I thought that when I wrote:
(function (msg){alert(msg)})
then a new unnamed function would be created like function ""(msg) ...
but then why doesn't this work?
(function (msg){alert(msg)});
('SO');
Why does it need to be in the same line?
Could you please point me some posts or give me an explanation?
Drop the semicolon after the function definition.
(function (msg){alert(msg)})
('SO');
Above should work.
DEMO Page: https://jsfiddle.net/e7ooeq6m/
I have discussed this kind of pattern in this post:
jQuery and $ questions
EDIT:
If you look at ECMA script specification, there are 3 ways you can define a function. (Page 98, Section 13 Function Definition)
1. Using Function constructor
var sum = new Function('a','b', 'return a + b;');
alert(sum(10, 20)); //alerts 30
2. Using Function declaration.
function sum(a, b)
{
return a + b;
}
alert(sum(10, 10)); //Alerts 20;
3. Function Expression
var sum = function(a, b) { return a + b; }
alert(sum(5, 5)); // alerts 10
So you may ask, what's the difference between declaration and expression?
From ECMA Script specification:
FunctionDeclaration :
function Identifier ( FormalParameterListopt ){ FunctionBody
}
FunctionExpression :
function Identifieropt ( FormalParameterListopt ){ FunctionBody
}
If you notice, 'identifier' is optional for function expression. And when you don't give an identifier, you create an anonymous function. It doesn't mean that you can't specify an identifier.
This means following is valid.
var sum = function mySum(a, b) { return a + b; }
Important point to note is that you can use 'mySum' only inside the mySum function body, not outside. See following example:
var test1 = function test2() { alert(typeof test2); }
alert(typeof(test2)); //alerts 'undefined', surprise!
test1(); //alerts 'function' because test2 is a function.
Live Demo
Compare this to
function test1() { alert(typeof test1) };
alert(typeof test1); //alerts 'function'
test1(); //alerts 'function'
Armed with this knowledge, let's try to analyze your code.
When you have code like,
function(msg) { alert(msg); }
You created a function expression. And you can execute this function expression by wrapping it inside parenthesis.
(function(msg) { alert(msg); })('SO'); //alerts SO.
It's called a self-invoked function.
What you are doing when you call (function(){}) is returning a function object. When you append () to it, it is invoked and anything in the body is executed. The ; denotes the end of the statement, that's why the 2nd invocation fails.
One thing I found confusing is that the "()" are grouping operators.
Here is your basic declared function.
Ex. 1:
var message = 'SO';
function foo(msg) {
alert(msg);
}
foo(message);
Functions are objects, and can be grouped. So let's throw parens around the function.
Ex. 2:
var message = 'SO';
function foo(msg) { //declares foo
alert(msg);
}
(foo)(message); // calls foo
Now instead of declaring and right-away calling the same function, we can use basic substitution to declare it as we call it.
Ex. 3.
var message = 'SO';
(function foo(msg) {
alert(msg);
})(message); // declares & calls foo
Finally, we don't have a need for that extra foo because we're not using the name to call it! Functions can be anonymous.
Ex. 4.
var message = 'SO';
(function (msg) { // remove unnecessary reference to foo
alert(msg);
})(message);
To answer your question, refer back to Example 2. Your first line declares some nameless function and groups it, but does not call it. The second line groups a string. Both do nothing. (Vincent's first example.)
(function (msg){alert(msg)});
('SO'); // nothing.
(foo);
(msg); //Still nothing.
But
(foo)
(msg); //works
An anonymous function is not a function with the name "". It is simply a function without a name.
Like any other value in JavaScript, a function does not need a name to be created. Though it is far more useful to actually bind it to a name just like any other value.
But like any other value, you sometimes want to use it without binding it to a name. That's the self-invoking pattern.
Here is a function and a number, not bound, they do nothing and can never be used:
function(){ alert("plop"); }
2;
So we have to store them in a variable to be able to use them, just like any other value:
var f = function(){ alert("plop"); }
var n = 2;
You can also use syntatic sugar to bind the function to a variable:
function f(){ alert("plop"); }
var n = 2;
But if naming them is not required and would lead to more confusion and less readability, you could just use them right away.
(function(){ alert("plop"); })(); // will display "plop"
alert(2 + 3); // will display 5
Here, my function and my numbers are not bound to a variable, but they can still be used.
Said like this, it looks like self-invoking function have no real value. But you have to keep in mind that JavaScript scope delimiter is the function and not the block ({}).
So a self-invoking function actually has the same meaning as a C++, C# or Java block. Which means that variable created inside will not "leak" outside the scope. This is very useful in JavaScript in order not to pollute the global scope.
It's just how JavaScript works. You can declare a named function:
function foo(msg){
alert(msg);
}
And call it:
foo("Hi!");
Or, you can declare an anonymous function:
var foo = function (msg) {
alert(msg);
}
And call that:
foo("Hi!");
Or, you can just never bind the function to a name:
(function(msg){
alert(msg);
})("Hi!");
Functions can also return functions:
function make_foo() {
return function(msg){ alert(msg) };
}
(make_foo())("Hi!");
It's worth nothing that any variables defined with "var" in the body of make_foo will be closed over by each function returned by make_foo. This is a closure, and it means that the any change made to the value by one function will be visible by another.
This lets you encapsulate information, if you desire:
function make_greeter(msg){
return function() { alert(msg) };
}
var hello = make_greeter("Hello!");
hello();
It's just how nearly every programming language but Java works.
The code you show,
(function (msg){alert(msg)});
('SO');
consist of two statements. The first is an expression which yields a function object (which will then be garbage collected because it is not saved). The second is an expression which yields a string. To apply the function to the string, you either need to pass the string as an argument to the function when it is created (which you also show above), or you will need to actually store the function in a variable, so that you can apply it at a later time, at your leisure. Like so:
var f = (function (msg){alert(msg)});
f('SO');
Note that by storing an anonymous function (a lambda function) in a variable, your are effectively giving it a name. Hence you may just as well define a regular function:
function f(msg) {alert(msg)};
f('SO');
In summary of the previous comments:
function() {
alert("hello");
}();
when not assigned to a variable, yields a syntax error. The code is parsed as a function statement (or definition), which renders the closing parentheses syntactically incorrect. Adding parentheses around the function portion tells the interpreter (and programmer) that this is a function expression (or invocation), as in
(function() {
alert("hello");
})();
This is a self-invoking function, meaning it is created anonymously and runs immediately because the invocation happens in the same line where it is declared. This self-invoking function is indicated with the familiar syntax to call a no-argument function, plus added parentheses around the name of the function: (myFunction)();.
There is a good SO discussion JavaScript function syntax.
My understanding of the asker's question is such that:
How does this magic work:
(function(){}) ('input') // Used in his example
I may be wrong. However, the usual practice that people are familiar with is:
(function(){}('input') )
The reason is such that JavaScript parentheses AKA (), can't contain statements and when the parser encounters the function keyword, it knows to parse it as a function expression and not a function declaration.
Source: blog post Immediately-Invoked Function Expression (IIFE)
examples without brackets:
void function (msg) { alert(msg); }
('SO');
(this is the only real use of void, afaik)
or
var a = function (msg) { alert(msg); }
('SO');
or
!function (msg) { alert(msg); }
('SO');
work as well. the void is causing the expression to evaluate, as well as the assignment and the bang. the last one works with ~, +, -, delete, typeof, some of the unary operators (void is one as well). not working are of couse ++, -- because of the requirement of a variable.
the line break is not necessary.
This answer is not strictly related to the question, but you might be interested to find out that this kind of syntax feature is not particular to functions. For example, we can always do something like this:
alert(
{foo: "I am foo", bar: "I am bar"}.foo
); // alerts "I am foo"
Related to functions. As they are objects, which inherit from Function.prototype, we can do things like:
Function.prototype.foo = function () {
return function () {
alert("foo");
};
};
var bar = (function () {}).foo();
bar(); // alerts foo
And you know, we don't even have to surround functions with parenthesis in order to execute them. Anyway, as long as we try to assign the result to a variable.
var x = function () {} (); // this function is executed but does nothing
function () {} (); // syntax error
One other thing you may do with functions, as soon as you declare them, is to invoke the new operator over them and obtain an object. The following are equivalent:
var obj = new function () {
this.foo = "bar";
};
var obj = {
foo : "bar"
};
There is one more property JavaScript function has. If you want to call same anonymous function recursively.
(function forInternalOnly(){
//you can use forInternalOnly to call this anonymous function
/// forInternalOnly can be used inside function only, like
var result = forInternalOnly();
})();
//this will not work
forInternalOnly();// no such a method exist
It is a self-executing anonymous function. The first set of brackets contain the expressions to be executed, and the second set of brackets executes those expressions.
(function () {
return ( 10 + 20 );
})();
Peter Michaux discusses the difference in An Important Pair of Parentheses.
It is a useful construct when trying to hide variables from the parent namespace. All the code within the function is contained in the private scope of the function, meaning it can't be accessed at all from outside the function, making it truly private.
See:
Closure (computer science)
JavaScript Namespacing
Important Pair of Javascript Parentheses
Another point of view
First, you can declare an anonymous function:
var foo = function(msg){
alert(msg);
}
Then you call it:
foo ('Few');
Because foo = function(msg){alert(msg);} so you can replace foo as:
function(msg){
alert(msg);
} ('Few');
But you should wrap your entire anonymous function inside pair of braces to avoid syntax error of declaring function when parsing. Then we have,
(function(msg){
alert(msg);
}) ('Few');
By this way, It's easy understand for me.
When you did:
(function (msg){alert(msg)});
('SO');
You ended the function before ('SO') because of the semicolon. If you just write:
(function (msg){alert(msg)})
('SO');
It will work.
Working example: http://jsfiddle.net/oliverni/dbVjg/
The simple reason why it doesn't work is not because of the ; indicating the end of the anonymous function. It is because without the () on the end of a function call, it is not a function call. That is,
function help() {return true;}
If you call result = help(); this is a call to a function and will return true.
If you call result = help; this is not a call. It is an assignment where help is treated like data to be assigned to result.
What you did was declaring/instantiating an anonymous function by adding the semicolon,
(function (msg) { /* Code here */ });
and then tried to call it in another statement by using just parentheses... Obviously because the function has no name, but this will not work:
('SO');
The interpreter sees the parentheses on the second line as a new instruction/statement, and thus it does not work, even if you did it like this:
(function (msg){/*code here*/});('SO');
It still doesn't work, but it works when you remove the semicolon because the interpreter ignores white spaces and carriages and sees the complete code as one statement.
(function (msg){/*code here*/}) // This space is ignored by the interpreter
('SO');
Conclusion: a function call is not a function call without the () on the end unless under specific conditions such as being invoked by another function, that is, onload='help' would execute the help function even though the parentheses were not included. I believe setTimeout and setInterval also allow this type of function call too, and I also believe that the interpreter adds the parentheses behind the scenes anyhow which brings us back to "a function call is not a function call without the parentheses".
(function (msg){alert(msg)})
('SO');
This is a common method of using an anonymous function as a closure which many JavaScript frameworks use.
This function called is automatically when the code is compiled.
If placing ; at the first line, the compiler treated it as two different lines. So you can't get the same results as above.
This can also be written as:
(function (msg){alert(msg)}('SO'));
For more details, look into JavaScript/Anonymous Functions.
The IIFE simply compartmentalizes the function and hides the msg variable so as to not "pollute" the global namespace. In reality, just keep it simple and do like below unless you are building a billion dollar website.
var msg = "later dude";
window.onunload = function(msg){
alert( msg );
};
You could namespace your msg property using a Revealing Module Pattern like:
var myScript = (function() {
var pub = {};
//myscript.msg
pub.msg = "later dude";
window.onunload = function(msg) {
alert(msg);
};
//API
return pub;
}());
Anonymous functions are functions that are dynamically declared at
runtime. They’re called anonymous functions because they aren’t
given a name in the same way as normal functions.
Anonymous functions are declared using the function operator instead
of the function declaration. You can use the function operator to
create a new function wherever it’s valid to put an expression. For
example, you could declare a new function as a parameter to a
function call or to assign a property of another object.
Here’s a typical example of a named function:
function flyToTheMoon() {
alert("Zoom! Zoom! Zoom!");
}
flyToTheMoon();
Here’s the same example created as an anonymous function:
var flyToTheMoon = function() {
alert("Zoom! Zoom! Zoom!");
}
flyToTheMoon();
For details please read http://helephant.com/2008/08/23/javascript-anonymous-functions/
Anonymous functions are meant to be one-shot deal where you define a function on the fly so that it generates an output from you from an input that you are providing. Except that you did not provide the input. Instead, you wrote something on the second line ('SO'); - an independent statement that has nothing to do with the function. What did you expect? :)

What is this? (function(){ })() [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicates:
What does this JavaScript snippet mean?
Location of parenthesis for auto-executing anonymous JavaScript functions?
(function(){
//something here...
})() <--//This part right here.
What exactly is this )()?
What if I change it to this ())?
(function(){
//something here...
}()) <--//Like this
This declares an anonymous function and calls it immediately.
The upside of doing this is that the variables the function uses internally are not added to the current scope, and you are also not adding a function name to the current scope either.
It is important to note that the parentheses surrounding the function declaration are not arbitrary. If you remove these, you will get an error.
Finally, you can actually pass arguments to the anonymous function using the extra parentheses, as in
(function (arg) {
//do something with arg
})(1);
See http://jsfiddle.net/eb4d4/
They are the same.
There has to be a parenthesis either around the function definition or around the function call to make it valid Javascript syntax, but it doesn't matter which you use.
To demonstrate what it does, using a named function it would be:
function something() {}
// parenthesis around the function reference:
(something)();
// parenthesis around the function call:
(something());
It's an anonymous function that gets called immediately the () calls the function and there are ( and ) wrapping the whole thing.
( // arbitrary wrapping
(function() { // begin anon function
}) // end anon function
() // call the anon function
) // end arbitrary wrapping
The first one just wraps the function in ( ) so that it can call the function immediately with the ()
(function(){
alert('Hi');
})();
Alerts Hi, while
function(){
alert('Hi');
}
Doesn't do anything since your function is never executed.
That's simply an anonymous function. The () parens call the function immediately, instead of waiting for it to be called elsewhere.
Its an immediately invoked anonymous function. ()) would not work because you need () around the function before you can call it with ().
Sorta equivalent to:
function a(){}
a();
This is declaring an anonymous function and then immediately executing it. This is common for creating scoped variables.
In JavaScript, function definition is a literal - which means, it's an expression with the value of the Function object.
If you put () right after it, you effectively call the function right after defining it.

Anonymous Member Pattern Export/Import Function

I'm a bit confused. What is the purpose of the parameters when you initiate an anonymous member pattern designated below:
(function (<ParameterA>) {
})(<ParameterB>);
I understand that Parameter A is used to designate the scope of the function is this true?
Is ParameterB where you export the function?
Finally, I often see script indicating the following:
})(jQuery || myfunc);
Does that mean they're exporting these or returning these objects? And what's the point of using the two pipes (||); It a field goal thing?
Thanks in advance. Looking forward to interesting discussion.
Parameter A does not designate the scope of the function. The function's position determines the scope of the function. ParameterB is not where you export the function. In fact, the way this is set up, there is no pointer to the function anywhere which makes it an "anonymous function." In other words, as is, the function itself is un-exportable. Usually when you talk about exporting things, you're talking about exporting variables that you defined inside anonymous functions. For example, here I am exporting the function my_inner_function from an anonymous function.
(function (<ParameterA>) {
// export this function here.
window.my_inner_function = function() {
...
};
})(<ParameterB>);
Usually, the point of anonymous functions is that you have all kinds of variables that you don't want to export because you don't want to possibly muck with other code.
(function (<ParameterA>) {
// convert could be defined somewhere else too, so to be on the safe side
// I will hide it here in my anonymous function so nobody else can
// reference it.
var convert = function() {
...
};
})(<ParameterB>);
This is particularly important when you compress your Javascript and get function names like a and b.
(function (<ParameterA>) {
// So compressed!
var a = function() {
...
};
})(<ParameterB>);
(function () {
// Another compressed thing! Good thing these are hidden within anonymous
// functions, otherwise they'd conflict!
var a = function() {
...
};
})();
Now this
(function (<ParameterA>) {
})(<ParameterB>);
is the same thing as
// Assume ParameterB is defined somewhere out there.
(function () {
var ParameterA = ParameterB;
})();
Which gives you an idea why you'd use the parameters. You may find the parameter approach less confusing, or you may want to make it clear that you don't want to affect "by value" variables such as numbers and strings.
As others have pointed out, a || b is spoken as "a or b" and means "a if a evaluates to true, otherwise b, no matter what b is."
Edit
To answer your question, when you get to })(); the () causes the anonymous function to run. Remember that Javascript engines will first parse all code to make sure the syntax is correct, but won't actually evaluate/execute any code until it reaches that code. Hence, it's when the anonymous function runs that var ParameterA = ParameterB; gets evaluated. Here are some examples that hopefully help.
var ParameterB = "hello";
(function () {
var ParameterA = ParameterB;
// alerts "hello" because when this line is evaluated ParameterB is still
// "hello"
alert(ParameterA);
})(); // () here causes our anonymous function to execute
ParameterB = "world";
Now in this example, the function is no longer anonymous because it has
a pointer. However, it acts the same as the previous example.
var ParameterB = "hello";
var myFunction = function () {
var ParameterA = ParameterB;
// alerts "hello" because when this line is evaluated ParameterB is still
// "hello"
alert(ParameterA);
};
myFunction();
ParameterB = "world";
In this example, I change the order of the last 2 lines and get different
results.
var ParameterB = "hello";
var myFunction = function () {
var ParameterA = ParameterB;
// alerts "world" because when this line is evaluated ParameterB has
// already changed.
alert(ParameterA);
};
// notice that I moved this line to occur earlier.
ParameterB = "world";
myFunction();
The code block above executes an anonymous function immediately after declaring it.
ParameterA is a parameter to the anonymous function you are declaring
ParameterB is the value you are passing to ParameterA
So the function you declared will be executed immediately, passing ParameterB as the value for ParameterA.
The jQuery || myFunc block means this: use jQuery as the argument unless it is not defined, in which case use myFunc.
Edit:
This is often used when defining jQuery plugins to avoid conflicts with the $ variable if multiple javascript libraries are being used. So you would make your plugin definition a function that accepts $ as a parameter, which you would execute immediately, passing jQuery as the value to $.
Example (from jQuery docs):
(function( $ ){
$.fn.myPlugin = function() {
// Do your awesome plugin stuff here
};
})( jQuery );
The result of the above code block will be a plugin definition where you are guaranteed that $ will be an alias for jQuery.
For parts 1 and 2, ParameterA could be used to alias a nested hierarchy. (ie: YAHOO.util.Event passed in as ParameterB, can be used as "e" in ParameterA.) That way, inside the anonymous function, you wouldn't be typing out the full namespace path. [I know you're a jquery guy, but the yahoo namespace is longer, and illustrates the point better :)] Alternatively, you could just manually store the reference in a var inside the function.
the jquery || myFunc syntax is shorthand for "use jquery if it is truthy/available, or myFunc if it is not".
It's sort of like var toUse = jQuery !== undefined ? jQuery : myFunc;
This is because javascript allows falsy value evaluation without converting the objects fully to a boolean. ie: undefined is falsy, "" is falsy, null is falsy.
The alternative can be used to detect if a method or property is even available with &&.
ie: var grandParent = person && person.parent && person.parent.parent;
This will only be defined if the person has a parent, and their parent has a parent. Any failure along the && leading up to the last statement will result in grandParent being undefined.
Lastly, the parens around the || shortcut syntax are basically executing the function immediately after the declaration, passing the evaluated value into the anonymous function.
ie: (function(a, b) { return a + b; })(2,3)
Will immediately execute and return 5. In practice, this anonymous function execution could be used with the module pattern to establish a set of public methods which use private functions that themselves do not appear in the page's namespace. This is more in depth than your original question, but you can check out this article for more information: http://yuiblog.com/blog/2007/06/12/module-pattern/
ParameterA is referencing the value passed in at ParameterB. This:
(function (<ParameterA>) {
})(<ParameterB>);
Is sort of the same as this:
function test(<ParameterA>) {
}
test(<ParameterB>);
The difference is that this way you are using a closure to not have conflicting functions in the global namespace.
For the second part: the || work sort of like param = jQuery ? jQuery : myFunc. It passes in jQuery if it is defined, or myFunc if it isn't.
With your first part:
(function (<ParameterA>) {
})(<ParameterB>);
This means that the variable known as ParameterB outside the function will be known as ParameterA inside the function. This is known as a self-executing function, because the function is called as soon as it is defined. It means that you can use ParameterA inside the function without overriding a variable that exists outside the function.
For instance:
(function($){
})(jQuery);
This means that you can have $ as, for instance, Mootools outside the function and as jQuery inside it.
With your second part:
})(jQuery || myfunc);
This calls the function passing the jQuery variable if it exists, and myfunc if it does not. I don't quite know why you'd do this...

Categories

Resources