Assuming the following:
var first = {
bob: null,
jim: null,
sue: null
},
second = {};
I'd like to be able to loop over the properties of first
and define getters/setters on second
for each; something like the following:
for (var name in first) {
Object.defineProperty(second, ('' + name), {
get: function() {
return first[name];
},
set: function(value) {
first[name] = value;
}
});
}
The problem is the getters/setters seem to only affect the last property iterated over, in this case sue
.
However, the following seems to work just fine:
var second = {
get bob() {
return first['bob'];
},
set bob(value) {
first['bob'] = value;
},
get jim() {
return first['jim'];
},
set jim(value) {
first['jim'] = value;
},
get sue() {
return first['sue'];
},
set sue(value) {
first['sue'] = value;
}
};
I know this has to be something obvious I'm missing, but I couldn't seem to find another question on here that accurately addresses how to accomplish this.
Thanks in advance!