javascript - jQuery $.extend() - how to not add new members to the first object if they don't exist? -
i stumbled on small problem when extending javascript objects using jquery. when executing
var item = $.extend(options.itemdefaults, item);
options.itemdefaults
extended properties in item
, result passed item
. far, good.
but next time line executed, options.itemdefaults
has property values item
had, instead of original defaults. defaults lost!
i realize store defaults object in temporary variable, , extend temporary variable instead, seems bit lengthy. there way i'm after (overriding default values supplied ones, taking defaults when no values supplied, not changing default object) without detour?
update: seems wasn't easy around hoped. when
var defaults = options.itemdefaults; var $item = $.extend(defaults, { attributemodel: options.attributemodel }, item); defaults = undefined
in each iteration, still add properties item
on options.itemdefaults
! how around this?
try,
var item = $.extend(true, {}, options.itemdefaults, item);
the true
flag indicates deep copy must made.
we use empty object {}
target defaults not tampered with.
properties of options.itemdefaults
, , item
copied empty object.
Comments
Post a Comment