替换对象's属性,其中包含JavaScript中另一个对象的属性,不包含库

Replacing object's properties with properties from another object in JavaScript, without libraries

本文关键字:属性 JavaScript 一个对象 包含库 包含 对象 替换      更新时间:2024-03-04

我一直在使用jQuery.extend来替换像这样的默认属性

var Car = function(options){
    var defaultOptions = {
        color: "hotpink",
        seats: {
            material: "fur",
            color: "black",
            count: 4
        },
        wheels: 4
    }
    this.options = $.extend(true,{},defaultOptions,options); 
}
var myCar = new Car({
    color: "blue",
    seats: {
        count: 2,
        material: "leather"
    }
});
alert(myCar.options.color); // "blue"
alert(myCar.options.seats.color); // "black"
alert(myCar.options.seats.count); // 2

虽然它效果很好,但我想知道在没有任何库的情况下实现类似结果的最佳方法。我只想在函数中定义一些默认设置,并用参数中的设置替换它们,每次这样做时都要包含一个库,这太过分了。

基本上它只是for..in的递归使用。您可以在源代码中看到jQuery实现的完整源代码(它的行号会随着时间的推移而腐烂,但它可能会保留在core.js中)。

这里有一个非常基本的即兴表演:

function deepCopy(src, dest) {
    var name,
        value,
        isArray,
        toString = Object.prototype.toString;
    // If no `dest`, create one
    if (!dest) {
        isArray = toString.call(src) === "[object Array]";
        if (isArray) {
            dest = [];
            dest.length = src.length;
        }
        else { // You could have lots of checks here for other types of objects
            dest = {};
        }
    }
    // Loop through the props
    for (name in src) {
        // If you don't want to copy inherited properties, add a `hasOwnProperty` check here
        // In our case, we only do that for arrays, but it depends on your needs
        if (!isArray || src.hasOwnProperty(name)) {
            value = src[name];
            if (typeof value === "object") {
                // Recurse
                value = deepCopy(value);
            }
            dest[name] = value;
        }
    }
    return dest;
}

您可以模仿jQuery的api"extend",就像楼上所说的那样。我认为没有比这更好的方法了。所以,我认为jQuery的api是合适的。

在ES6中引入了扩展运算符。

var Car = function(options){
    var defaultOptions = {
        color: "hotpink",
        seats: {
            material: "fur",
            color: "black",
            count: 4
        },
        wheels: 4
    }
    this.options = {...defaultOptions, ...this.options};
}
var myCar = new Car({
    color: "blue",
    seats: {
        count: 2,
        material: "leather"
    }
});

参考文献:

  • https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax
  • 如何在ES6+中将两个javascript对象合并在一起
  • 或者您可以使用Object.assign