JavaScript equivalent of jQuery's extend method

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

    To get the result in your code, you would do:

    function extend(a, b){
        for(var key in b)
            if(b.hasOwnProperty(key))
                a[key] = b[key];
        return a;
    }
    

    Keep in mind that the way you used extend there will modify the default object. If you don't want that, use

    $.extend({}, default, config)
    

    A more robust solution that mimics jQuery's functionality would be as follows:

    function extend(){
        for(var i=1; i<arguments.length; i++)
            for(var key in arguments[i])
                if(arguments[i].hasOwnProperty(key))
                    arguments[0][key] = arguments[i][key];
        return arguments[0];
    }
    
    0 讨论(0)
  • 2020-11-28 03:33

    It helps me a lot when I develop with pure javascript.

    function extends(defaults, selfConfig){
         selfConfig = JSON.parse(JSON.stringify(defaults));
         for (var item in config) {
             if (config.hasOwnProperty(item)) {
                 selfConfig[item] = config[item];
             }
         }
         return selfConfig;
    }
    
    0 讨论(0)
提交回复
热议问题