JavaScript equivalent of jQuery's extend method

前端 未结 8 2061
小鲜肉
小鲜肉 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:25

    I prefer this code that uses my generic forEachIn, and does not mangle the first object:

    function forEachIn(obj, fn) {
        var index = 0;
        for (var key in obj) {
            if (obj.hasOwnProperty(key)) {
                fn(obj[key], key, index++);
            }
        }
    }
    
    function extend() {
        var result = {};
        for (var i = 0; i < arguments.length; i++) {
            forEachIn(arguments[i],
                function(obj, key) {
                    result[key] = obj;
                });
        }
        return result;
    }
    

    If you really do want to merge stuff into the first object, you can do:

    obj1 = extend(obj1, obj2);
    

提交回复
热议问题