JavaScript equivalent of jQuery's extend method

前端 未结 8 2039
小鲜肉
小鲜肉 2020-11-28 02:57

Background

I have a function that takes a config object as an argument. Within the function, I also have default object. Each of those

8条回答
  •  离开以前
    2020-11-28 03:09

    You can use Object.assign.

    var defaults = {key1: "default1", key2: "default2", key3: "defaults3"};
    var config = {key1: "value1"};
    
    var settings = Object.assign({}, defaults, config); // values in config override values in defaults
    console.log(settings); // Object {key1: "value1", key2: "default2", key3: "defaults3"}
    

    It copies the values of all enumerable own properties from one or more source objects to a target object and returns the target object.

    Object.assign(target, ...sources)
    

    It works in all desktop browsers except IE (but including Edge). It has mitigated mobile support.

    See for yourself here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign

    About deep copy

    However, Object.assign does not have the deep option that jQuery's extend method have.

    Note: you can generally use JSON for a similar effect though

    var config = {key1: "value1"};
        var defaults = {key1: "default1", key2: "default2", keyDeep: {
            kd1: "default3",
            kd2: "default4"
        }};
        var settings = JSON.parse(JSON.stringify(Object.assign({}, defaults, config))); 
        console.log(settings.keyDeep); // Object {kd1: "default3", kd2: "default4"}
    

提交回复
热议问题