Extending an object with multiple properties in JavaScript

后端 未结 3 1688
清酒与你
清酒与你 2021-02-19 16:39

I have a global JavaScript object with multiple properties and functions that I am creating it this way:

myObject = {};

I thought that I can ea

3条回答
  •  栀梦
    栀梦 (楼主)
    2021-02-19 17:02

    Or, something cleaner:

    function extend(target, source){
        for(prop in source){
            target[prop] = source[prop];
        }
    }
    

    If you use it the following way:

    var objA = {a: "a"};
    var objB = {b: "b", c: "c"};
    extend(objA, objB);
    

    The result will be:

    objA = {a: "a", b: "b", c: "c"};
    

提交回复
热议问题