在 JavaScript 中基于其他 2 个对象创建一个对象

javascriptweb developmentfront end technologyobject oriented programming更新于 2024/1/10 0:12:17

假设我们有两个 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) },
}

Note that a and b need to stay the same.

示例

其代码为 −

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] }

相关文章


有用资源