Here is a code
var collection = (function (){
var x = 0;
return {
y : x,
get : function(){return x},
set : function(n) { x = n}
}
}());
collection.set(1000);
Why collection.y != collection.get()
?
In JavaScript, a closure is a function that references variables in the outer scope from its inner scope. The closure preserves the outer scope inside its inner scope. To understand the closures, you need to know how the lexical scoping works first.
Advantages of closures Variables in closures can help you maintain a state that you can use later. They provide data encapsulation. They help remove redundant code. They help maintain modular code.
Definition of closure 1 : an act of closing : the condition of being closed closure of the eyelids business closures the closure of the factory. 2 : an often comforting or satisfying sense of finality victims needing closure also : something (such as a satisfying ending) that provides such a sense.
This is called a JavaScript closure. It makes it possible for a function to have "private" variables. The counter is protected by the scope of the anonymous function, and can only be changed using the add function. A closure is a function having access to the parent scope, even after the parent function has closed.
y is not a "pointer" to x. When created the closure you simply copied the value of x at that moment into y, and every time you call get()/set() you only operate on x (no relation to y)
You are not setting collection y when you call collection.set(1000)
Because y will store the value 0, and will not read it from x. While get() will read the variable x every time you call it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With