Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript closure

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() ?

like image 756
Salvatore DI DIO Avatar asked Sep 03 '09 19:09

Salvatore DI DIO


People also ask

What is closure JavaScript?

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.

What is the benefit of closure in JavaScript?

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.

What is closure explain?

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.

What is closure in JavaScript w3schools?

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.


3 Answers

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)

like image 75
Amro Avatar answered Sep 20 '22 15:09

Amro


You are not setting collection y when you call collection.set(1000)

like image 31
Daniel Moura Avatar answered Sep 18 '22 15:09

Daniel Moura


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.

like image 42
Aziz Avatar answered Sep 20 '22 15:09

Aziz