oop - JavaScript: Assign values of arguments object as fields in an Object -
i converting object constructor form of
function obj(arg1, arg2, arg3, arg4, ..., argn-1, argn) { this.name = arg1; this.field = arg2; this.etc = arg3; ... } //obj
to form of
function obj() { var args = array.prototype.slice.call(arguments); var defaultargs = { 'field' : default ... }; ... check args, etc } //obj
here code far:
function dsobj () { var args = array.prototype.slice.call(arguments); var defaultargs = { 'fields' : values or functions returning values ... }; var options = {}; (var in defaultargs) { if (typeof(args[i] == 'undefined')) { options[i] = defaultargs[i]; } else { options[i] = args[i]; } //check if user supplied argument } //for each possible argument (var name in options) { this.name = options[name]; //trying make fields - wrong } //for each final parameter } //constructor dsobj
so, need last part of above constructor. started programming javascript around week ago, , education goes far reading beginners syntax book. so, if there better way other stupid , direct way, please let me know. reason can't reference options array above of methods written object in way use "this.method" paradigm. please. guise. help.
i think need bracket notation instead of dot one:
for (var name in options) { this[name] = options[name]; }
be aware for...in
loops iterate inherited properties, may want check options.hasownproperty(name)
avoid that.
also note when iterate defaultargs
, i
each property. args
indexed numbers, not custom keys.
you can use like
function dsobj () { var argnames = ['fields', /*...*/], defaultargs = [ /* ..., ... */]; (var i=0, l=arguments.length; i<l; ++i) { this[argnames[i]] = arguments[i] || defaultargs[i]; } }
or if arguments[i]
can falsy, then
this[argnames[i]] = arguments[i] !== void 0 ? arguments[i] : defaultargs[i];
Comments
Post a Comment