I have a Javascript constructor with an object containing all of its fields, and functions that read/write to them:
function myObj(){
var _settingsStore {
setting1: 1, //default value
setting2: 2, //default value
}
//gets/sets _settingsStore.settingName, does other stuff
function _genericSet(settingName, settingValue){}
function _genericGet(settingName){}
I'd like to programmatically create properties around each of the fields:
for (var _setting in _settingsStore){
var _str = _setting.toString();
Object.defineProperties(this, {
_str: {
get: function() {return _genericGet(_str)},
set: function(value) {return _genericSet(_str, value)}
}
})
}
My intent is for _str to be purely a variable, and that myObj.setting1
and myObj.setting2
should be defined. Instead, the loop attempts to define myObj._str
twice:
Uncaught TypeError: Cannot redefine property: _str
What's going on? And is there a way to get my desired behavior?
EDIT: To clarify, this is what I effectively want to happen, just unrolled outside of the loop:
Object.defineProperties(this, {
settings1: {
get: function() {return _genericGet("settings1")},
set: function(value) {return _genericSet("settings1", value)}
},
settings2: {
get: function() {return _genericGet("settings2")},
set: function(value) {return _genericSet("settings2", value)}
},
//and so on, if there are more of them
})