Before understanding closure we have to know about scopes in javascript
Example 1 :-
var _name = pName ; // Private variable
this.getName = function (){
return _name;
};
}
var human = new person("Ram");
human._name // throws error because its closure to person fun
human.getName() ; // will return name of the person
Example 1 :-
var x = 1; //Global for below functions
function a(){
x = 2; //refers to Global x
var y = 3; //New local variable for func a
function b(){
y = 4 ; //refers to parent funct a
var x = 5;// local variable for func b no relation to global x
}
b();
}
a();
Closure :- Is nothing but a closed box where inside member variables are accessed only by member functions.
function person (pName){var _name = pName ; // Private variable
this.getName = function (){
return _name;
};
}
var human = new person("Ram");
human._name // throws error because its closure to person fun
human.getName() ; // will return name of the person
No comments:
Post a Comment