Closure Review Again

Lexical scoping

function init() {  
  var name = "demo"; // name is a local variable created by init
  function demo1() { // demo1() is the inner function, a closure
    alert(name); // use variable declared in the parent function    

init() has a local variable name and a function demo1,demo1()
is an inner function defined in init() and in only available in init()
demo1() has no local variable,but it can asscess to the outer function which is init() and it can use the variable in parent function scope.


function Func1(){  
        var name = "demo";
        function name1(){
        return name1;

var newFunc1 = Func1();  
newFunc1();//this is a Closure  

The following result is the same as the first one,the differences is ---the inner functionname1() was return from the outer function before being executed.The result remain the same,but the local variable is only available for the duration of it's parent function's execution,for example the Fun1() has finished executed,the name variable is no longer be accessible.

Because the newFunc1 has become a closure. A closure is a special kind of object that combines two things: a function, and the environment in which that function was created.The environment consists of any local variables that were in-scope at the time that the closure was created. In this case,newFunc1 is a closure that incorporates both the name1() function and the name variable existed when the closure was created.

Closure and Partial function

function makeAdder(x) {  
  return function(y) {
    return x + y;

var add1 = makeAdder(1);  
var add10 = makeAdder(10);    1

console.log(add1(2));  // 3  
console.log(add10(2)); // 12  

In this example, we have defined a function makeAdder(x) which takes a single argument x and returns a new function. The function it returns takes a single argument y, and returns the sum of x and y.

The makeAdder is a function factory - it creates functions which can add a specific value to their argument. In the above example we use our function factory to create two new functions — one that adds 5 to its argument, and one that adds 10.

add5 and add10 are both closures. They share the same function body definition, but store different environments.