最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - jQuery $.extend() - how to not add new members to the first object if they don't exist? - Stack Overflow

programmeradmin1浏览0评论

I just stumbled over a small problem when extending javascript objects using jQuery. When executing

var item = $.extend(options.itemDefaults, item);

options.itemDefaults is extended with the properties that are already in item and the result is passed to item. So far, so good.

But the next time this line is executed, options.itemDefaults has all the property values that item had, instead of the original defaults. My defaults are lost!

I realize I could simply store the defaults object in a temporary variable, and extend the temporary variable instead, but it seems a bit lengthy. Is there a way to do what I'm after (overriding default values with supplied ones, taking defaults when no values are supplied, but not changing the default object) without that detour?

Update: It seems this wasn't as easy to get around as I hoped. When I do

var defaults = options.itemDefaults;
var $item = $.extend(defaults, { attributeModel: options.attributeModel }, item);
defaults = undefined 

in each iteration, I still add properties from item on options.itemDefaults! How do I get around this?

I just stumbled over a small problem when extending javascript objects using jQuery. When executing

var item = $.extend(options.itemDefaults, item);

options.itemDefaults is extended with the properties that are already in item and the result is passed to item. So far, so good.

But the next time this line is executed, options.itemDefaults has all the property values that item had, instead of the original defaults. My defaults are lost!

I realize I could simply store the defaults object in a temporary variable, and extend the temporary variable instead, but it seems a bit lengthy. Is there a way to do what I'm after (overriding default values with supplied ones, taking defaults when no values are supplied, but not changing the default object) without that detour?

Update: It seems this wasn't as easy to get around as I hoped. When I do

var defaults = options.itemDefaults;
var $item = $.extend(defaults, { attributeModel: options.attributeModel }, item);
defaults = undefined 

in each iteration, I still add properties from item on options.itemDefaults! How do I get around this?

Share Improve this question edited Jul 26, 2010 at 8:10 Tomas Aschan asked Jul 26, 2010 at 8:00 Tomas AschanTomas Aschan 60.7k62 gold badges262 silver badges420 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 11

Try,

var item = $.extend(true, {}, options.itemDefaults, item);

The true flag indicates that a deep copy must be made.

We use an empty object {} as the target so the defaults are not tampered with.

Properties of options.itemDefaults, and item will be copied into the empty object.

发布评论

评论列表(0)

  1. 暂无评论