Javascript - Object Utility

/*
* Copy the enumerable properties of p to o, and return o.
* If o and p have a property by the same name, o's property is overwritten.
* This function does not handle getters and setters or copy attributes.
*/
function extend(o, p) {
    for (prop in p) { // For all props in p.
        o[prop] = p[prop]; // Add the property to o.
    }
    return o;
}

/*
* Copy the enumerable properties of p to o, and return o.
* If o and p have a property by the same name, o's property is left alone.
* This function does not handle getters and setters or copy attributes.
*/
function merge(o, p) {
    for (prop in p) { // For all props in p.
        if (o.hasOwnProperty[prop]) continue; // Except those already in o.
        o[prop] = p[prop]; // Add the property to o.
    }
    return o;
}

/*
* Remove properties from o if there is not a property with the same name in p.
* Return o.
*/
function restrict(o, p) {
    for (prop in o) { // For all props in o
        if (!(prop in p)) delete o[prop]; // Delete if not in p
    }
    return o;
}

/*
* For each property of p, delete the property with the same name from o.
* Return o.
*/
function subtract(o, p) {
    for (prop in p) { // For all props in p
        delete o[prop]; // Delete from o (deleting a
        // nonexistent prop is harmless)
    }
    return o;
}

/*
* Return a new object that holds the properties of both o and p.
* If o and p have properties by the same name, the values from o are used.
*/
function union(o, p) { return extend(extend({}, o), p); }

/*
* Return a new object that holds only the properties of o that also appear
* in p. This is something like the intersection of o and p, but the values of
* the properties in p are discarded
*/
function intersection(o, p) { return restrict(extend({}, o), p); }

/*
* Return an array that holds the names of the enumerable own properties of o.
*/
function keys(o) {
    if (typeof o !== "object") throw TypeError(); // Object argument required
    var result = []; // The array we will return
    for (var prop in o) { // For all enumerable properties
        if (o.hasOwnProperty(prop)) // If it is an own property
            result.push(prop); // add it to the array.
    }
    return result; // Return the array.
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值