使用Javascript将对象复制到对象

我们可以使用ECMAScripts 6中引入的Object.assign方法轻松地将许多对象的所有属性复制到单个对象中。下面的示例将创建三个对象,并将其他两个对象的属性分配给作业对象。

let obj1 = {
		name : "John",
		occupation : "programmer",
		salary : 3000
}

let obj2 = {
		company : "xyz",
		__proto__ : {bonus : 1.6, position : "manager"}
}

let job = {};

Object.assign(job, obj1, obj2);

console.log(job.name + " works as a " + job.occupation + " in " + job.company + " company with monthly salary of " + job.salary + " and bonus of " + job.salary * job.bonus + " in the " + job.position + " level");

结果如下…

John works as a programmer in xyz company with monthly salary of 3000 and bonus of NaN in the undefined level

对象属性名称既可以是字符串也可以是符号,可以通过上述方法复制一个。正如你从上面可以看到的,只有一个属性,该方法将无法复制,并且这是对象的原型属性,其中Object.assign方法不会将对象的原型属性分配给另一个对象,并且该作业对象想要访问该奖金,并获得“未定义”的位置原型的属性。

Leave a Reply

Be the First to Comment!

avatar
  Subscribe  
Notify of