Outside Scopes and contexts closures are one of the most vital features in JavaScript language. Knowing how to implement closure is crucial to a successful and well written JavaScript code. On this chapter I will guide you on how to easy understand the concept of closures and how to implement it in the wright way.
What is a closure in JavaScript?
Wikipedia: In computer science, a closure is a first-class function with free variables that are bound in the lexical environment. Such a function is said to be “closed over” its free variables. A closure is defined within the scope of its free variables, and the extent of those variables is at least as long as the lifetime of the closure itself.
Basically a closure is explained very simply by Tim Caswell as a function within another scope that has access to all the variables within the outer scope.
How to use Closures
The following examples shows how we call the function that generate another function or group of functions but hides all the stare in private variables within the closure. The function message is included in the Person function.
Note: According to the rules of closures all the child scopes have access to the parent scope or variables within a function.
Basically this means that the parent variable:
function Person(name, age) {
var person = 'name: ' + name + ' Age: ' + age;
return function message() {
console.log(person);
};
}
// Generate the closure
var PersonName = Person('Lea', 27); //Use the closure
PersonName();
Output: name: Lea Age: 27
Closures for events and callbacks
Ryan Dahl (the creator of node.js) used javascript in otder to simplyfy this operation. C for instance doesn’t have closures and that make non-blocking code difficult to write in C. Let give some example using setTimeout (setTimeout is a non-blocking function call) for a better understanding.
function Person(name, age) {
this.person = 'name: ' + name + ' Age: ' + age;
}
Person.prototype.messageoutput = function messageoutput() {
console.log(this.person);
}
var Sofia = new Person("Sofia", 27);
setTimeout(function(){
Sofia.messageoutput();
}, 1000);
Output: name: Sofia Age: 27
Functions in JavaScript are first-class values. The whole this context helps in designing classical OO API’s.