Programmatically defining Javascript properties in the object constructor -
i have javascript constructor object containing of fields, , functions read/write them:
function myobj(){ var _settingsstore { setting1: 1, //default value setting2: 2, //default value } //gets/sets _settingsstore.settingname, other stuff function _genericset(settingname, settingvalue){} function _genericget(settingname){}
i'd programmatically create properties around each of fields:
(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 _str purely variable, , myobj.setting1
, myobj.setting2
should defined. instead, loop attempts define myobj._str
twice:
uncaught typeerror: cannot redefine property: _str
what's going on? , there way desired behavior?
edit: clarify, want happen, unrolled outside of 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 on, if there more of them })
i'm starting over. if want use setters , getters work, , each object has on store hidden in constructor, , wanted reuse generic functions, this:
function myobj(){ var _settingsstore = { setting1: 1, //default value setting2: 2, //default value } (var _setting in _settingsstore){ makegetset(this, _setting, _settingstore); } } function makegetset(obj, key, store) { object.defineproperty(obj, key, { get: function() { return _genericget(key, store)} set: function(val) {_genericset(key, val, store)} }) } function _genericget(key, store){ var val = store[key]; // manipulate val return val } function _genericset(key, val, store){ // manipulate new val store[key] = val }
i don't know sort of manipulations you're doing when getting/setting, of maybe shortened.
also, make _settingsstore
generic, , use variable scope value storage since need anyway.
Comments
Post a Comment