this[ "set" + i ] = function(val) { properties[i] = val; }; This code only defines a function but doesn't execute its contents right now, and as functions "capture" the variables defined outside of them if you change the value of i then it will "change" in properties [i] too. In other words the `i` in properties[i] is the same that you use for the loop.
If you use a closure you can define a local variable that gets the value (not the reference!) of the current index so that won't change afterwards. Sounds complicated but it really isn't - once you get it :) On Dec 18, 5:52 pm, "pablo fernandez" <fernandezpabl...@gmail.com> wrote: > That Does it too!! > > I still don't get why 'i' keeps always the last value if you don't do > var i = j; :S > > On Thu, Dec 18, 2008 at 1:11 PM, Balazs Endresz > > > > <balazs.endr...@gmail.com> wrote: > > > I've just had a look at it and where this issue comes up in the book > > there's a new variable declared (like on page 153). No need to pass > > the argument this way, moreover not that easy to mistype: > > > for ( var j in properties ) { (function(){ > > var i=j; > > ... > > > I can't believe no one has spotted > > this:http://www.apress.com/book/errata/275 > > > On Dec 18, 4:53 pm, Pablo Fernandez <fernandezpabl...@gmail.com> > > wrote: > >> That did it, although I had to add this too > > >> -- }).call(this,i); > > >> in order to pass the parameter > > >> Thanks Balazs!!! > > >> On 18 dic, 12:29, Balazs Endresz <balazs.endr...@gmail.com> wrote: > > >> > Oops, I didn't notice it: you have to pass the `i` variable too: > >> > for ( var i in properties ) { (function(i){ > > >> > That's why you need the closure at all. Without that you will get the > >> > last property from all getters. > > >> > The reference of `this` will always change if you put it in an > >> > additional function, doesn't matter if it's inside an instantiated > >> > object. Well, you can call that either design error or feature too :) > > >> > On Dec 18, 4:18 pm, Pablo Fernandez <fernandezpabl...@gmail.com> > >> > wrote: > > >> > > another thing... why inside the anonymous function 'this' refers to > >> > > 'window' ?? it's totally misleading... > > -- > Fernandez, Pablo.