top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

What are Javascript closures?

+7 votes
379 views

When would you use them?

posted Feb 5, 2014 by Merry

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

2 Answers

0 votes

Closures are functions that refer to independent (free) variables.

In short, variables from the parent function of the closure remain bound from the parent's scope.

Consider the following:
function init() {
var name = "Mozilla"; // name is a local variable created by init
function displayName() { // displayName() is the inner function, a closure
alert (name); // displayName() uses variable declared in the parent function
}
displayName();
}
init();

init() creates a local variable name and then a function called displayName(). displayName() is the inner function (a closure) — it is defined insideinit(), and only available within the body of that function . Unlike init(), displayName() has no local variables of its own, and instead reuses the variable name declared in the parent function.

Run the code and see that this works. This is an example of lexical scoping: in JavaScript, the scope of a variable is defined by its location within the source code (it is apparent lexically) and nested functions have access to variables declared in their outer scope.

answer Feb 6, 2014 by Hiteshwar Thakur
0 votes

Closures are not hard to understand once the core concept is grokked. However, they are impossible to understand by reading any academic papers or academically oriented information about them!

An Example of a Closure
Two one sentence summaries:
a closure is the local variables for a function - kept alive after the function has returned, or
a closure is a stack-frame which is not deallocated when the function returns. (as if a 'stack-frame' were malloc'ed instead of being on the stack!)
The following code returns a reference to a function:

function showName (firstName, lastName) {

var nameIntro = "Your name is ";
// this inner function has access to the outer function's variables, including the parameter
function makeFullName () {

return nameIntro + firstName + " " + lastName;

}
return makeFullName ();

}

showName ("Michael", "Jackson"); // Your name is Michael Jackson

Most JavaScript programmers will understand how a reference to a function is returned to a variable in the above code. If you don't, then you need to before you can learn closures. A C programmer would think of the function as returning a pointer to a function, and that the variables sayAlert and say2 were each a pointer to a function.

answer Feb 6, 2014 by Amit Kumar Pandey
Similar Questions
+9 votes

How to add behavior to an element using javascript?

...