Need your inputs on th closure function in javascript.
Give me one real time example where we implement the closure function in java script?
Need your inputs on th closure function in javascript.
Give me one real time example where we implement the closure function in java script?
A closure is an inner function that has access to the outer (enclosing) function’s variables—scope chain. The closure has three scope chains: it has access to its own scope (variables defined between its curly brackets), it has access to the outer function’s variables, and it has access to the global variables.
The inner function has access not only to the outer function’s variables, but also to the outer function’s parameters. Note that the inner function cannot call the outer function’s arguments object, however, even though it can call the outer function’s parameters directly.
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");
closures as explains in MDN are functions that refer to the environment in which they were created because of reference to global variables. They give the example
function init() {
var name = "Mozilla";
function displayName() {
alert(name);
}
return displayName();
}
var myFunc = init();
In this example displayName
uses name
which is defined in init
scope.