JavaScript Closure is the inner function that the access to its outer function's variables. Closure has 3-scopes:-
1: It has the access to it's enclosing function.
2: It has the access to the variables withing its own scope.
3: It has the access to all the global variables.
The inner function's scope is not only limited to its outer function's variable but as well as to its parameters.
Example of Javascript Closure:
function whatIsMyName(firstName, lastName){
var prefix = "My name is: ";
function showName() { //This function can access variable and parameters of the outer function
return prefix + firstName + lastName;
}
showName();
}
whatIsMyName("Dinesh", "Rawat");
/* Result:
My name is: My name is: Dinesh Rawat
*/
Rules of Javascript closure's:
1: It has the access of the variables and parameters of its outer function event if the outer function returns
2: Closure contains the references of outer function variables, not the actual values.
Ex:-
function test() {
var x = 20;
return {
getId: function() {
return x;
};
setId: function(newX) {
x = newX;
}
}
}
var T = new test();
T.getId(); // Prints 10
T.setId(90);
T.getId(); //Prints 90 not 10
0 Comment(s)