jQuery $ .extend而不覆盖目标属性 [英] jQuery $.extend without overriding target properties

查看:544
本文介绍了jQuery $ .extend而不覆盖目标属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以在不覆盖已设置属性的情况下扩展对象? 在下面的示例中,我正在寻找一种为猫添加2个翅膀的方法,但要保持它的4条腿.

Is it possible to extend an object without overriding the properties that are already set? In the following example I'm looking for a way to add 2 wings to the cat, but keepings it's 4 legs.

var cat  = { legs: 4 };
var bird = { legs: 2, wings: 2 }

// some references in my application to the original cat
var some_cat = cat;

$.extend( cat, bird );

// expected { legs: 4, wings: 2 }
console.log( some_cat );

更新

我忘记在原始问题/示例中弄清楚了,但重要的是,它修改了原始的cat对象.

I forgot to make it clear in the original question / example, but it is important that it modifies the original cat object.

推荐答案

尝试类似-

for (prop in bird) {
    if(!cat.hasOwnProperty(prop)) {
        cat[prop] = bird[prop];
    }
}

cat = {腿:4,翅膀:2}之后

After cat = {legs: 4, wings: 2}

这篇关于jQuery $ .extend而不覆盖目标属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆