手写原理 | Object.assign

Object.assign方法将所有可枚举和自有属性从一个或多个源对象复制到目标对象,返回修改后的对象

语法

1
Object.assign(target, ...sources)

参数

  • target:目标对象
  • sources:源对象

注意

  1. 源对象可以有N个
  2. 相同属性,后面的会覆盖前面的
  3. Symbol类型的属性会被拷贝,而且不会跳过那些值为null和undefined的源对象

实现思路

  1. 判断目标对象是否为正确,不能为null或者defined
  2. 使用for…in…循环遍历出所有可枚举属性(可以使用hasOwnProperty判断)并且复制给目标对象

手写实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
function myObjectAssign() {
let target = Array.prototype.shift.call(arguments);

if (target == null) { // undefined == null 为true
throw new Error('Cannot convert null or undefined to object.')
};

// Object装箱
const obj = Object(target);

for (let i = 0; i < arguments.length; i++) {
const source = arguments[i];
if (source != null) {
for (let key in source) {
// 注意for in会遍历原型链上的属性
if (source.hasOwnProperty(key)) {
obj[key] = source[key];
};
};
};
};
return obj;
};

// test
const obj = { a: 1 };
const copy = myObjectAssign({}, obj);
console.log(copy); // { a: 1 }