views:

662

answers:

4

When you wrap your JavaScript 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, but I've never actually known what this practice is called.

+15  A: 

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){.

Nick Craver
Strictly speaking a closure is a side-effect of the function. This isn't a closure, it's a function. In fact, there probably isn't even a closure being created in this case, since the function's contents aren't accessible from outside it. See http://jibbering.com/faq/notes/closures/
Jani Hartikainen
@Jani - That's what a closure does... it's specifically for (in this case) hiding the contents from the outside, while having them accessible to anything inside. Even the link you provided gives this *exact* definition: "The simple explanation of a Closure is that ECMAScript allows inner functions; function definitions and function expressions that are inside the function bodes of other functions. And that those inner functions are allowed access to all of the local variables, parameters and declared inner functions within their outer function(s)."
Nick Craver
@Nick, the line you quote is referring to the way the Identifier Resolution process works, not specifically with the formation of a closure, continuing with the quote: "A *closure* is formed when one of those inner functions is made accessible outside of the function in which it was contained, so that it may be executed after the outer function has returned." So if no *inner* function is made available to the outside, a closure is *not* formed -what @Jani points out-, IMO the term *closure* is sometimes overused nowadays.
CMS
@CMS - You can't tell from the example if that's the case or not though. For example what if the next line is `window.method = doSomething;`? The OP is asking a general question about the wrapper, and in my experience, *most* of the time you're exposing *something* to the outside, though I concede that's not *always* the case. I clarified a bit above that I'm answering the common case, not specifically his (partial) example.
Nick Craver
@Nick, yeah, the example is incomplete. Yes, you almost always expose something to the outside, in the case of a *function* (or an object containing a property that references to a local function) a closure is formed. Thanks for the clarification.
CMS
But he's not asking about what happens to variables captured in the anonymous function (which is what closures are). He's asking about an anonymous function declared as a function expression being immediately called. You are answering the wrong question.
slebetman
@slebetman - His question **specifically** mentioned scoping problems on pages, how are you saying this isn't answering the question? It's an anonymous function, being immediately called and it's *probably* a closure (though we can't be sure without the entire code), what exactly did I leave out?
Nick Craver
@Nick: A function is **not** a closure. Don't get your terminologies mixed up. A closure is the variable shared by functions. A function can **create** a closure but it in itself is not a closure. It's like calling an oven a cake. A cake is not an oven but an oven may be used to bake a cake.
slebetman
@slebetman - I don't believe I said a function *is* a closure, you won't get any debates from me there (in fact, it's on the first line of the answer: " **creating** a closure"). I'm saying this is *probably* **creating** a closure, as in that's its main purpose (though, again, we can't tell without see the entirety of the code). I apologize if you're not reading that, I thought the clarification half an hour ago articulated this pretty clearly, I'll try to refine it to make it even clearer.
Nick Craver
@Nick: Remember if you use window or variables like document (which are evaluated as window.document), you are using javascript's global variables, and are not, in fact, using any closed variables.
Mike Axiak
@Mike - In my example in response to CMS like `window.method = doSomething;` you see from the question `doSomething` is in question...you're providing access to that scope with this reference, creating a closure, and you *are* using closed variables in there when the function's called.
Nick Craver
@Nick, In your example it is, but in my experience, most times people use this pattern, they are only accessing global variables (whether it's jquery, window, document, etc). Such pattern is thus not usually using closures, and thus we don't need to confuse people with this terminology just because it's "the hip term". Also, I think what bothers me is that while a closure could possibly be used, it's not the *essential* feature going on here. Yes, variables are used too, but we don't call this pattern a variable, do we?
Mike Axiak
@Mike and Nick: I think Mike is correct, but to throw some more dust in this discussion, I'll quote Flanagan's *Definitive Guide*: “JavaScript functions are a combination of code to be executed and the scope in which to execute them. This combination of code and scope is known as a *closure* in the computer science literature. All JavaScript functions are closures. These closures are only interesting, however, in the case discussed above: when a nested function is exported outside the scope in which it is defined. When a nested function is used in this way, it is often explicitly called a clo…
Marcel Korpel
@Mick and Nike: …sure.” (5th ed., p. 144)
Marcel Korpel
@Marcel: I'm not sure who Flanagan is, but Landin's original paper described a closure as having an environment and variables, and used the term anonymous functions to refer to the functions themselves. (The paper is easily accessible for free online.)
Mike Axiak
Marcel Korpel
+14  A: 

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.

Jani Hartikainen
I personally call it a self-calling-function. The moment I say that phrase most seasoned javascript developer know what I'm talking about.
slebetman
I call it anonymous scoping function
Here Be Wolves
+15  A: 

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.

palswim
I'm not sure how you call this a side-effect...if you wanted to execute the code immediately (and *not* a closure) why wrap it in a function in the first place? It's a direct and intentional effect.
Nick Craver
@Nick Craver: see edit. I meant an effect, but the intended effect.
palswim
@Nick: a closure is a possible side effect. A function is **not** a closure. A function without a name is called an anonymous function, mistakenly called a closure by those not familiar with functional languages. In javascript things declared in braces `(..)` are expressions, so that is an anonymous function expression. All expressions return something. In the case of function expressions it returns a reference to a function. None of the things above are called closures in the traditional sense. A closure is a variable shared between functions, not the function itself.
slebetman
@slebetman - You didn't read the comments above, or my updated answer from 20 minutes ago, I clarified exactly this: "It's only a 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."
Nick Craver
@Nick: even then it's not a closure, it's an anonymous function. The two concepts are separate though closures depend on functions.
slebetman
@Nick: to use your own phrasing to explain: `when something inside that scope is exposed to an outer scope` then that `something` is called a closure (not the scoping mechanism itself which is a function).
slebetman
@slebetman - You're right I should have added "creating" there was well (it was already in the answer, so I thought people could read this easily...). I've updated to hopefully make it crystal clear, even when taking snippets of the answer.
Nick Craver
+2  A: 

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

Sean McMillan