Closure

What is Closures?

Closures is a function with access to parent scope even after the parent function is executed. It is a way of creating private variable or function.


Private variable

Following is an example for creating private variable. Here name is private variable which can be accessed only in innerFunc even after mainFunction is executed

p { color: red }
function mainFunction() {
var name = 'yahoo'; //outer function scope
function innerFunc() { // Closure function which has access to name variable
alert(name);
}
return innerFunc;  // returns function defination reference
}

var myFunc = mainFunction();  // now myFunc has displayName function defination reference
myFunc();  // innerFunc function called and alert box displays name which is outer variable for innerFunc

Performance issue

It is not necessary to create functions within other functions if closures are not needed for a particular task, as it will negatively affect script performance both in terms of processing speed and memory consumption.

For example, when creating a new object/class, methods should normally be attached to the object's prototype instead of defining into the object constructor. The reason is that whenever the constructor is called, the methods would get reassigned for every object creation.

function newObject(name, message) {
this.name = name.toString();
this.message = message.toString();
this.getName = function() { // here new defination is created for getName for every 'newObject' call or creation
return this.name;
};

this.getMessage = function() {
return this.message;
};
}

The above can be written by using prototype as follows

function newObject(name, message) {
this.name = name.toString();
this.message = message.toString();
}

// here new defination is created for getName for only 'newObject' function
MyObject.prototype.getName = function() {
return this.name;
};

MyObject.prototype.getMessage = function() {
return this.message;
};