What is this practice called in JavaScript? - javascript

When you wrap your JavaScript code in a function like this:
(function(){
var field = ...;
function doSomthing(){...
...
})();
I noticed that this fixes scoping problems for me on a lot of web pages. What is this practice called?

The pattern is called self-invocation, a self-invoking function. It can create a closure, but that is an effect of the pattern (perhaps the intended effect), not the pattern itself.

To clarify a bit for the comments below, most of the time it's creating a closure, it keeps your variables scoped to that local closure, as to not create global variables, it both keeps things clean and avoids any potential unwanted changes to those variables.
There are some excellent answers here that explain the why a bit more: How does a javascript closure work?
It's only a creating closure when something inside that scope is exposed to an outer scope, which is usually the case, but I can't be sure for your example without seeing more code. If nothing is exposed then no closure's created...otherwise it's just an anonymous function executing immediately.
The })(); format at the end, as opposed to }); is actually calling that closure to execute immediately, with no parameters. If you had something in it, for example })(something); then that something would be passed as the first argument here: (function(somethingParam){.

The wrapping function is called an anonymous (it has no name and it isn't assigned to a variable) self-executing (it executes immediately, by itself) function.
I don't remember seeing an exact name for this pattern, but it prevents variable from leaking into global scope.

Ben Alman presents an interesting argument on the commonly use terminology for this "pattern".
His blog post about it is here (http://benalman.com/news/2010/11/immediately-invoked-function-expression/).
If his post is too long for you here is my summary (I still recommend reading it as this summary leaves out a lot):
If you want a named function to be self executing/invoking it would should look like this:
// Hello, my name is "foo". I am a named function.
// When I am invoked I invoke my self when I am invoked.
function foo(){
foo();
}
If you want an anonymous function to be self executing/invoking it should look like this:
// Hello, I have no name...
// (though I am assigned to the variable "foo" it's not who I am).
// When I am invoked I invoke my self when I am invoked.
// In ECMAScript 5 I no longer work. :-(
var foo = function(){
arguments.callee();
};
If you want an anonymous function to be immediately executed/invoked it should look like this:
// Hello, I have no name. I am immediately invoked.
// People sometimes call me a "self-invoking anonymous function"...
// even though I don't invoke myself.
// Ben Alman calls me an "Immediately-Invoked Function Expression"...
// or "iffy" for short.
(function(){ /...code.../ }());
My own thoughts on the matter:
The other answers are correct; what you are asking about is commonly referred to as a "self invoking anonymous function."
However, that terminology doesn't accurately reflect what is really happening; "Immediately-Invoked Function Expression" (aka "iffy", for short) seems like a more appropriate term.
Fun facts to impress your friends:
You can create an Iffy like this, too:
!function(){
alert("immediately invoked!");
}();
or
+function(){
alert("immediately invoked!");
}();
or if you are really cRaZy ( example ):
!1%-+~function(){
alert("immediately invoked!");
}();
in most browsers (if not all, I'm not sure) and the effect will be the same (facebook uses the ! version).

Douglas Crockford and the YUI team call it the module pattern.

What is this practice called?
It's called an immediately-invoked function expression, in short: IIFE. It defines a function in an expression, which is then executed on its own (without assigning the function to any identifier). It sometimes is also called immediately executed function expression (IEFE).
Before Ben Alman wrote his blog post on them, they were also known as self-invoking (anonymous) functions, a term which became uncommon since then. It was technically imprecise, hinting at a recursive invocation which does not actually happen.
For details on the syntax see Explain the encapsulated anonymous function syntax and Location of parenthesis for auto-executing anonymous JavaScript functions?.
I noticed that this fixes scoping problems for me on a lot of web pages.
Yes, the purpose of this pattern is to introduce an extra scope by executing a function.
The pattern also is sometimes extended with a return value, known as the (revealing) module pattern, or with a name for the function to allow recursive invocations.

It's been around longer than "patterns". It is a common idiom in scheme/lisp primarily used for encapsulation especially when doing meta programming.

Related

Declaration on ExtJS

I'm working on some code, and I came across the following situation inside an archive .js --
(function(Ext) { ..."Here have 2 Ext.Define"... })(Ext);
This code runs normally, but i can't find because the declaration is like that, what is the difference of use simply 2 Ext.Define, the guy who did that code don't work here anymore, but my colleagues said that according to him this is more faster to render, this information proceeds? and if it is, what kind of situations i can use that?
That is an example of a self executing function.
There are some situations when developers use self invoking functions (also known as anonymous functions), like for example when you want an auto-run capability to your app.
My guess is that the previous developer, that worked in your project, wanted just this. Execute the function as soon as it was defined, as some sort of auto-run mechanism.
Also you could use a self invoking function when for example you want to regularly updates a webpage, by using for example setInterval.
(function refreshDB(){
setTimeout(refreshDatabase, 60000);
})()
A self executing function is executed as soon as it is defined.
You can look at it this way:
function(Ext) { ..."Here have 2 Ext.Define"... } represents the definition/declaration of the function, which takes one argument Ext
(function declaration)(arguments), in your case the arguments is only one, namely an object called Ext. This is simply the convention on how to declare and execute a self invoking function in JavaScript.
Also, the following syntax:
(function(arg){console.log(arg)})('Hello World!')
has the same outcome as
! function(arg){console.log(arg)}('Hello World!')
which is just another way of declaring a self-invoking function.

JS: What's the difference between a ! closure and () closure? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
What does the exclamation mark do before the function?
So I was going back and looking over some of my own code as well as some other javascript code and I realized that a while back when I started writing javascript libraries I was using closures that looked something like this:
(function( window, document, undefined ) {
// code
})( window, document );
But then I saw some bootstrap code and I changed to this syntax:
! function (window, document, undefined) {
// code
}(window, document);
Now, if I'm not wrong (and please correct me if I am), placing the '!' in front of my anonymous function just causes it to be treated as '()' then returns (into nowhere?) a boolean value of whether the value returned by the function was not undefined, null, or empty.
What I'm wondering is, is there really a difference between using the '!()' syntax over '()()'? Are there certain browsers that will complain?
Any thoughts are appreciated, thanks! XD
What you're asking about is self-calling functions, otherwise known as IIFE (immediately invoked function expression). Which is a different thing from a closure. Although it does create a closure (indeed, all functions in javascript create closures, not just IIFE).
It's understandable that you may confuse the two issues though, since IIFE are usually introduced in the context of explaining closures. But be aware that they are different things. Closures are private, shared "global-like" variables. IIFE are functions that gets called immediately upon their definitions.
Now, how does IIFE work? The clue is in the name. It's the "FE" IIFE - function expression.
In javascript, as you know, there are two ways of creating functions - using function declarations:
function foo () {}
and using function expressions:
foo = function () {}
A function expression is simply a function declared in the context* of an expression. What are expressions in javascript? Simply any statement that evaluates something.
Traditionally, people recognize expressions as:
anything on the right side of the = sign
a = /* expression */
anything in braces
(/* expression */)
So traditionally those are the two "standard" ways for declaring function expressions:
foo = function(){}
and
(function(){})
And the second syntax makes it easy to then execute the function object returned by the expression. But, really, an expression is anywhere js does math (or logic, which is math anyway). So adding an operator to a function declaration also turns it into an expression. The following works because they are unary operators (meaning, they are legal without anything on the left hand side):
!function(){}()
+function(){}()
-function(){}() // I especially like this one because it
// looks like a command line switch
typeof function(){}()
But you can also use binary operators if you use some throw-away value or variable with it. The following also work:
x=function(){}()
0==function(){}()
1*function(){}()
2/function(){}()
Heck, you can even abuse the ternary operator:
0?0:function(){}() // valid and works!
There's nothing magical about it. It's not a specific syntax baked into javascript. Just like (function(){}()) is not a specific syntax for IIFE. It's just that when declared in an expression, functions return themselves as objects which can be called immediately.
But I'd advise against using any of the non-standard forms above though. For the same reason you asked this question - most javascript programmers are not used to seeing them and it can cause confusion. I myself didn't realize that you can do this until you asked the question. Still, it's a useful thing to know for when you need to write things like minifiers, code generators etc.
* I'm using "context" in it's traditional definition here not the javascript specific meaning of "context" as defined in the spec.
Nothing, they are just two different ways of achieving the same thing. The () is slightly more readable though.

What is this line at the top of some Greasemonkey scripts?

Background:
I have a self-taught hobbyist level of understanding of C++, which has translated into a similar understanding of javascript. As an attempt to understand javascript better, I decided to write a Greasemonkey script that would solve a problem with how Google handles multiple results from the same domain.
I wrote my script, and it was surprisingly easy. Now I feel like this script could be useful to others, so I'd like to release it. Before I do that though, I'd like to be certain I'm not releasing irresponsible code.
I know poor garbage collection is often cited as a problem with extensions, and did some research about what I would need to do in javascript to prevent that. It seems like the answer is any memory that is wrapped in a function will be reclaimed when that function exits. This seems to explain why a few popular scripts I looked at were wrapped in an otherwise useless function.
This leads me to these questions:
What should I do with my basic javascript function to ensure that it doesn't leak memory?
Is this, which I've seen in many scripts, an answer:
(function(){
//code goes here
})();
In the above code, what is the purpose of the first parentheses? It seems redundant to me.
While I was attempting to understand that line, I rewrote it as:
(function main(){
//code goes here
})
main();
The idea being that this was just calling the the previously unnamed function. This didn't work though, why?
I'm more interested in general answers, but in case it's needed here is my current code:
http://pastebin.com/qQWKfnJT
This pattern (wrapping a function in a pair of parenthesis and then placing another pair after the first pair) is called the " I mmediately I nvoked F unction E xpression" pattern (IIFE for short). What it does is define an anonymous function and then execute it immediately. The first set of parentheses mark the function as being an expression, rather than a statement. The second set execute the function returned from the first expression:
// This:
(function(){
// Todo: Add code
})();
// Translates *approximately* to this:
var _anonymous_function_2723113 = function() {
// Todo: Add code
};
_anonymous_function_2723113();
delete _anonymous_function_2723113;
As for why the function does not work when you give it a name, I would recommend reading up on kangaxx's article on the subject, especially where he touches on Named Function Expressions. The short of it is that when you have a named function expression (rather than a statement), the name is supposed to only be available to the function's scope.
So much for three and four - as for avoiding memory leaks, the IIFE is not a way to avoid memory leaks (as #elclanrs has pointed out, it merely helps you avoid polluting the global scope). To avoid memory leaks avoid circular references (and remember, closures can be a source of circular references).
Good luck, and enjoy yourself!
Here is an example, where anonymous functions can be used:
Lets have 4 elements with ids: id_1, id_2, id_3...
We want too loop over each of them and assign onclick event.
for (var i=0; i<5; i++) {
document.getElementById("id_"+i).onclick = function() {alert(i)}
}
When you click elements however each of them will alert the same - 4. The reason is that in the JavaScript closure only the last value is stored for local variables.
What you can do:
for (var i=0; i<5; i++) {
(function(n){
document.getElementById("id_"+n).onclick = function() {alert(n)};
})(i);
}
There are so many answers to this question in SO already... It's a self executing function. It's used in many cases to protect your code from the global scope. It's written in other ways too:
function(){}()
(function(){})()
(function(){}())
!function(){}()
(function(){}).call(this)

JavaScript notation: (function() { ... } )(); [duplicate]

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.

Confusing Javascript class declaration

I have some third-party Javascript that has statements like this:
FOO = function() {
...functions() ...
return { hash }
}();
It is working as designed but I'm confused by it. Can anybody define what this structure is doing? Is it just a weird way to create a class?
This is a technique that uses closure. The idiom is well-known, but confusing when you first see it. FOO is defined as the object that the outermost function() returns. Notice the parenthesis at the end, which causes the function to evaluate and return { hash }.
The code is equivalent to
function bar() {
...functions() ...
return { hash }
};
FOO = bar();
So FOO is equal to { hash }. The advantage of this is that hash, whatever it is, has access to stuff defined inside the function(). Nobody else has access, so that stuff is essentially private.
Google 'Javascript closure' to learn more.
Js doesn't really have classes, per se, but "prototypes". This means that no two objects are ever of the same "type" in the normal type-safe sense, and you can dynamically add members to one instance while leaving the other unmolested. (which is what they have done).
Believe it or not, the syntax they have used is probably the most lucid, as it doesn't try to hide behind some C-style class syntax.
Doug Crockford's Javascript: The Good Parts is a quick read, and the best introduction to OOP in js that I've come across.
That's not actually a class, just an object. I'd recommend reading this: http://javascript.crockford.com/survey.html
Because JavaScript doesn't have block scope, your choice is (mostly) to have all variable reside in global or function scope. The author of your snippet wants to declare some local variables that he doesn't want to be in the global scope, so he declares an anonymous function and executes it immediately, returning the object he was trying to create. That way all the vars will be in the function's scope.
The parans at the end make this the Module Pattern, which is basically a way to have a single instance of an object(Singleton) while also using private variables and functions.
Since there's closures hash, if it's itself an object or function, will have access to all variables declared within that anonymous Singleton object.
You're missing an open parens, but it is basically a way of usually hiding information within an object i.e. a way of setting up private and privelaged methods.
For example
var foo = (function() {
/* function declarations */
return { /* expose only those functions you
want to expose in a returned object
*/
}
})();
Take a look at Papa Crockford's Private Members in JavaScript. This is basically the pattern you are seeing, but in a slightly different guise. The function declarations are wrapped in a self-invoking anonymous function - an anonymous function that is executed as soon as it's declared. Since the functions inside of it are scoped to the anonymous function, they will be unreachable after the anonymous function has executed unless they are exposed through a closure created by referencing them in the object returned from the execution of the anonymous function.
It's generally referred to as the Module Pattern.

Categories