tags:

views:

122

answers:

4
+6  Q: 

Javascript closure

Hello,

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);

Could anybody explains me why collection.y != collection.get() ?

Regards

Salvatore

+2  A: 

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

Daniel Moura
Thanks Daniel
Salvatore DI DIO
+1  A: 

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.

Aziz
Thanks Aziz
Salvatore DI DIO
+1  A: 

Well the object you're setting collection to looks like this:

{
  y : 0,
  get : function(){return x},
  set : function(n) { x = n}                        
}

there's no x property to store state in (edit: to be fair it will get created, but y still has a closure on the 0 value so won't be updated), so what else were you expecting? Replace x with y and you should be ok.

annakata
it's very clear now, thanks
Salvatore DI DIO
+1  A: 

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)

Amro