I am new to Javascript and I am currently trying to understand the closure of it and it's use after going through many sites and w3schools which says "It makes it possible for a function to have "private" variables." http://www.w3schools.com/js/js_function_closures.asp , I am trying to understand it's use , I have found some links but I did not understand it still I do not understand how closure achieves private access like c++. When you explain please explain in details as I am a beginner
Asked
Active
Viewed 44 times
0
-
[Emulating private methods with closures Edit](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures#Emulating_private_methods_with_closures). MDN is a much better resource than W3Schools, by the way. – str Jun 22 '16 at 11:39
-
W3Schools is not the only resource available, Search the internet for good resources and see which makes sense, this is too generic a question. Eg: http://javascriptissexy.com/understand-javascript-closures-with-ease/ – Arathi Sreekumar Jun 22 '16 at 11:43
1 Answers
0
It's just declaring variables inaccesible from outer scope:
function Gen() {
var c = 0; // c is private here
this.next = function() {return ++c;}
}
var gen = new Gen();
console.log(gen.next()); // 1
console.log(gen.next()); // 2
console.log(gen.next()); // 3
We can't to get/set c
value directly, we must use exported interface(next
method).
So, inner counter value is incapsulated in the "private"
variable.
Ok, here is closure example, but meaning is same: scope
incapsulating.
function getGenerator() {
var c = 0;
return function() {return ++c; }
}
var a = getGenerator();
var b = getGenerator();
console.log(a()); // 1
console.log(a()); // 2
console.log(b()); // 1
console.log(a()); // 3

vp_arth
- 14,461
- 4
- 37
- 66