Ok, I try to create new object this way:
var src = {a:\'a\', b:\'b\', c:\'c\'};
var out = {};
for(var prop in src){
Object.defineProperty(out, prop,{
When you create a function inside a loop you create a closure around the variables used in that loop. In this case there is a closure around prop
. Each function (the getters) has a reference to prop
so when they are called later on (when the getter is used) they use the value in prop
which happens to be the last value that was assigned in the loop.
In other words, since the getter is called later, the value in prop
is whatever value it was last set to. defineProperty
, on the other hand, gets the correct value since there is no closure. It is called with the value at the time of the call rather than after the loop is complete.