在JavaScript中基于其他2个对象创建对象
假设我们有两个这样定义的JavaScript对象-
const a = {
   a: 1,
   af: function() { console.log(this.a) },
};
const b = {
   b: 2,
   bf: function() { console.log(this.b) },
};我们需要编写一个接受两个这样的对象的JavaScript函数。创建另一个将获取a和b属性的对象,如下所示-
const output = {
   a: 1,
   af: function() { console.log(this.a) },
   b: 2,
   bf: function() { console.log(this.b) },
}请注意,a和b需要保持相同。
示例
为此的代码将是-
const a = {
   a: 1,
   af: function() { console.log(this.a) },
};
const b = {
   b: 2,
   bf: function() { console.log(this.b) },
};
const extend = function(){
   let i, j, x, res=(arguments[0] || {});
   for (i = 1; i < arguments.length; i++) {
      const x = arguments[i];
      for (j in x) {
         if (x.hasOwnProperty(j)) {
            res[j] = x[j];
         }
      }
   }
   return res;
};
const c = extend({}, a, b);
console.log(c);输出结果
控制台中的输出将是-
{ a: 1, af: [Function: af], b: 2, bf: [Function: bf] }