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!
nameis being hoisted outside of the loop im guessing, can you try withletinstead ofvar, e.g:for (let name in first) {- also, you shouldn't need the weird string concatenation, just do:Object.defineProperty(second, name, {nameis last set as"sue"and then the getters/setters are called, and in their scope,nameis still"sue"because of how the non-intuitive way in which JS scopes work. Here's a blog post explaining the issue and how to fix it: robertnyman.com/2008/10/09/…