This question already has answers here:
What is the purpose of a self executing function in javascript?
(21 answers)
Closed 8 years ago.
I'm a beginner in programming and I just wonder about one thing. To be exact the syntax of (function(){...}).()
This question has been probably asked but as I don't know what it is and how to call it, I had very small luck finding anything about this topic.
I have been checking some scripts lately and I noticed that in some of them people use:
(function(){
...
}).(something) //
So far I'm guessing it's something like function which calls itself right away? How do we use it and what are the advantages of this. What do I put inside where 'something' is? also sometimes before it starts it also has $ sign.
Imagine a normal function:
function foo(){
...
}
Now let's call that function:
foo();
Instead of calling the function using its name, let's call it directly:
(function foo(){
...
})();
Since I don't use this function any where else, let's remove its name:
(function(){
...
})();
Want to pass a parameter to the function? Sure!
(function(something){
...
})(something);
Advantage of this? We have a scope!
(function(something){
var bar = 5; // Can't access this outside the function
})(something);
This allows you to define stuff outside of the global scope.
Your first example is an anonymous self-invoked function. So you are right, it calls itself straight away. If it had a name, that name would ONLY be visible inside those brackets (..).
The dollar-sign functions are short-hand for jQuery calls.
You are correct in that it a function that calls itself immediately, also called a self executing function.
The $ is just shorthand using jquery.
function(){} is declaring a function, while when we do
$(function() {}) it means we pass a function into another function $() as parameter, where this function will be executed by $() when the times met
it is much like
var a = function() { do something }
a();
will do something, in C# its like delegate, while in C++ it is like function pointer, in javascript it is made simple though where you can directly embed a function at the position where a parameter should be
Related
This question already has answers here:
What is the (function() { } )() construct in JavaScript?
(28 answers)
Closed 6 years ago.
Am still and again and forever trying to come to grips with javascript. I look at other scripts for inspiration and learning. Does somebody know what this is:
(function(args){})(moreArgs){});
It's the skeleton of jquery. Can somebody explain to me how this works?
Thanks!
Here is more of the skeleton:
( function( global, factory ) {
} )( typeof window !== "undefined" ? window : this, function( window, noGlobal ) {
return jQuery;
} );
TLDR; (func)(params); executes a function inplace with out having to assign the function to a separate variable.
Lets break this code down to it's smaller elements. Firstly the whole code is a self executing function. Consider we have a anonymous function.
var add = function (a,b) { return a + b; };
We can call this function like
add(1,2);
however we can also wrap our function in () and call it in the same way.
(add)(1,2);
Both will result in the add function being called. Because JavaScript does not differentiate between function literals and references to anonymous functions we can use the same format to call a function literal.
(function(a,b){ return a + b; }))(1,2);
It's this format your code is using to call the outer function. So why would we want to call a function in this way? Because namespace, or lack there of. JavaScript has a global mutable namespace. Global means that all of the language constructs are available in the same namespace that by default scripts are executed in. This would not be such a problem however everything in this namespace is mutable. So
Array = {};
Would redefine the array constructor function. Any other scripts on your page that are using Array would stop working if they have not already finished executing. This is bad as it yields unpredictable behaviour. So how do we fix this. One way is to place our entire program in a function. When your inside a closed function you no longer are in the global javascript namespace. Your in the function scope and your free to redefine Array if you feel the need(seriously though don't redefine Array).
So we have our function that protects our program form any other's running within a page but we have one problem. We have defined a function however we have not called it. Javascript is executed as it's read. When the VM reads the first line of your js file it will execute that line. This is not true of code with in a function. This code will only execute when the function is called. So as short hand () is added to the end of a defined function to ensure that function is called as soon as it has been loaded by the VM.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
JavaScript: var functionName = function() {} vs function functionName() {}
What is the difference between a function expression vs declaration in Javascript?
What is the right way to declare Javascript Function?
From codeacademy.com i got this way:
var someFunction = function(paramA, paramB){
// do some function here
}
But because my basic of programming is PHP, i prefer declare function with this way:
function someFunction(paramA, paramB){
// do some function
}
What I'm concern is which one is recommended way to declare function, I'm afraid if my preferred way have some consequences, but i love that way so much because it make my NetBeans Code Navigator can read all of my functions.
Both are acceptable. Indeed, you can also do:
foo = function bar() {
console.log(arguments.callee.name);
};
If you then call foo(), you'll see "bar" in the console.
The first method creates an anonymous function and assigns it to a variable.
The second method creates a named function and places it within the current scope.
The third method creates a named function and assigns it to a variable. However, this time, the name only exists within the scope of that function.
Declaring a function with a name (function name () {}) has the advantage that you can then call the function more easily from inside itself, as may be necessary for implementing a recursive algorithm. If you don't, you have to use arguments.callee.name in order to call a function within itself, but that is warned against in MDN.
All of that is a long-winded way of saying that either is acceptable and, if in doubt, you can't go much wrong with using named functions.
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.
This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
What is the purpose of wrapping whole Javascript files in anonymous functions like “(function(){ … })()”?
Hello all,
I have seen several JavaScript files using this notation:
Start of JavaScript file:
(function() {
// All functions go here.
// Can someone say what the wrapping nameless function is used for?
})();
Also with the prototype library, this seems possible:
function $() {
// Prototype $-wrapping function.
}
Can someone please explain the above two code fragments, their uses and their differences? Some keywords which would help me find more about this notation/technique (how it is named) would be helpful too so I can run a Google search on it... :)
Thanks!
In your first example, people surround their code in an anonymous function for scoping reasons, to avoid global namespace cluttering. That weird parentheses syntax is used to define and execute the function all in one step; the () at the end has the meaning of executing the function itself.
So inside that anonymous function you could define function apple(){} and it would only be accessible inside that anonymous function. This is good if you're making a library and want only certain things to clutter your global namespace.
Your second example is just a simple function called $. Many libraries like to use this name because it's short and concise, and since you need to type it every time you want to reference the libraries namespace, the shorter, the better.
I searched for "javascript wrapping function" and the first hit was this, which says:
This method doesn't add any new symbols to the global or LIB spaces.
I don't understand the second part of the question: function $() { ... } isn't a "nameless" function: it has the name $! If you like functions named $ it's the most straightforward way I know of to make such a thing.
An annonymous function is defined
function() {
}
and then immediately called
()
The extra () enclosing the function is to force the interpreter to treat the function as an expression. Javascript treats any statement starting with the function keyword as a declaration so it could not otherwise be immediatly called.
The purpose is to avoid polluting the global namespace. All variables defined in the function will be local to the function.
Google for module pattern.
retracted in favor of answer to: What is the purpose of wrapping whole Javascript files in anonymous functions like “(function(){ … })()”?
First one is called immediate function. You can read more about this function pattern here.
This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
Javascript: var functionName = function() {} vs function functionName() {}
Way 1:
function fancy_function(){
// Fancy stuff happening here
}
Way 2:
var fancy_function = function(){
// Fancy stuff happening here, too.
}
I use the former when I'm just defining a "normal" function that I'm gonna use one or several times and the latter when I'm passing it a callback for another function or so, but it looks to work fine in the both ways.
Is it really a difference in some way?
There is no difference to the function itself, but the latter gives you more flexibility as you have a reference to the function and it is different with regard to how it behaves if overwritten.
This allows you to achieve behaviours with the latter that you cannot achieve with the former; such as the following trick to "override" an existing function and then call the "base":
var myOriginalFunction = function() {
window.alert("original");
}
var original = myOriginalFunction;
var myOriginalFunction = function() {
window.alert("overridden");
original();
}
myOriginalFunction();
This gives you an alert "overridden", followed by an alert "original".
However, if you attempt this with the former notation, you'll find you get stuck in a never ending loop of alert "overidden".
In the first sample you are defining a named function -- that function will always be known by that name. Defining a different function with the same name will be an error (unless you assign to the window property directly). In the second sample, you are defining an anonymous function and assigning it as the value of a variable. You can change the value of the variable to any other function later as desired; losing, of course, any reference to the anonymous function in the process unless you've stored it elsewhere. So, you're not really doing the same thing in both cases, though you can treat it that way if you wish -- and make sure to define the function before it's used in the second case, though that's more a function of variables than functions per se.
function definition
function literal assignment
only difference is you can access the former instantly in certain cases whereas you have to wait for the assignment on the latter.
Don't run this in firebug console/interpreter to test it, rather test on a real html page.
say('spotted');
function say(msg){ alert(msg) }
The above will work, but if you defined a function literal with var say = function(){} below, it would complain that it isn't defined yet.
You can use either depending on the situation, both become the methods of the window object. The later is known as anonymous function.
As far as the function is concerned, they will behave identically.
See here for more details: http://javascript.about.com/library/blfunc.htm
Functions defined with the Function(){} style are available throughout the program, without having to be defined earlier in the code than where they are called. It's called 'hoisting', I believe.
so this works
cow('spotted');
function cow(color){ return 'cow is '+color; }
but this throws an error
cow('spotted');//cow isn't defined yet!
var cow=function(color){ return 'cow is '+color; }