今天看了段前端代码 :
// 加载数据方法 必须为 Promise 对象loadData: parameter => {return getAppPage(Object.assign(parameter, this.queryParam)).then((res) => {return res.data})}
const target = { a: 1 };
const source1 = { b: 2 };
const source2 = { c: 3 };Object.assign(target, source1, source2);
target // {a:1, b:2, c:3}
Object.assign 方法的第一个参数是目标对象,后面的参数都是源对象。
const target = { a: 1, b: 1 };
const source1 = { b: 2, c: 2 };
const source2 = { c: 3 };Object.assign(target, source1, source2);
target // {a:1, b:2, c:3}
const obj = {a: 1};
Object.assign(obj) === obj // true
typeof Object.assign(2) // "object"
Object.assign(undefined) // 报错
Object.assign(null) // 报错
let obj = {a: 1};
Object.assign(obj, undefined) === obj // true
Object.assign(obj, null) === obj // true
const target = { a: { b: 'c', d: 'e' } }
const source = { a: { b: 'hello' } }
Object.assign(target, source)
// { a: { b: 'hello' } }
const source = {get foo() { return 1 }
};
const target = {};Object.assign(target, source)
// { foo: 1 }
上面代码中,source 对象的 foo 属性是一个取值函数,Object.assign 不会复制这个取值函数,只会拿到值以后,将这个值复制过去。
const merge = (target, ...sources) => Object.assign(target, ...sources);
const merge = (...sources) => Object.assign({}, ...sources);