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?
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.
How to get a selected text inside a iframe. I my page i m having a iframe which is editable true. So how can i get the selected text in that iframe.
I would like to click a link in my page using javascript. I would like to Fire event handlers on the link without navigating. How can this be done? This has to work both in firefox and Internet ...
Heres the problem, In Masterpage, the google analytics code were pasted before the end of body tag. In ASPX page, I need to generate a script (google addItem tracker) using codebehind ClientScript ...
Is there a reliable way to access the client machine s clipboard using Javascript? I continue to run into permissions issues when attempting to do this. How does Google Docs do this? Do they use ...
I have a large javascript which I didn t write but I need to use it and I m slowely going trough it trying to figure out what does it do and how, I m using alert to print out what it does but now I ...
Is it possible for someone to give me a few pointers on how to display a multidimensional array in the form of a bar graph? The array is multidimensional, with three elements in each part - and the ...
Is it possible to reload a form after file-input change? I have a form where the user can chose an image for upload. I also have a php script which displays that image resized. I only wonder if it ...
I ve made a little forum and I want parse the date on newest posts like twitter, you know "posted 40 minutes ago ","posted 1 hour ago"... What s the best way ? Thanx.