//参考MDN Object.assign() 方法文档
1. Object.assign()
方法用于将所有可枚举属性的值从一个或多个源对象分配到目标对象。它将返回目标对象。
const target = { a: 1, b: 2 };
const source = { b: 4, c: 5 };
const returnedTarget = Object.assign(target, source);
console.log(target);
// expected output: Object { a: 1, b: 4, c: 5 }
console.log(returnedTarget);
// expected output: Object { a: 1, b: 4, c: 5 }
2. 语法
Object.assign(target,...sources)
target
目标对象。sources
源对象。
3:模拟一下 Object.assign() 方法的实现
let target = { a: 1, b: 2 };
let source1 = { b: 3, c: 4 };
Object.defineProperty(Object, "myAssign", {
value: function (target) {
if (target == null) {
throw new TypeError('目标对象不能为空')
}
var newObj = Object(target);
for (let i = 0; i < arguments.length; i++) {
let newObj = Object(target);
let source = arguments[i];
if (source) {
for (let key in source) {
let flag = Object.prototype.hasOwnProperty.call(source, key);
if (flag) {
newObj[key] = source[key]
}
}
}
}
return newObj;
}
})
let obj2 = Object.myAssign({}, target, source1);
console.log('obj2', obj2)