导航
assign(目标对象, 源对象1, 源对象2, 源对象3, ...)
const test1 = { a: 1, b: 2 };
const test2 = { b: 3, c: 4 };
const test3 = { c: 5, d: 6 };
const test4 = Object.assign(test1, test2, test3);
console.log(test1);
console.log(test2);
console.log(test3);
console.log(test4);
test4.a = 233;
console.log(test1, test4); // 修改 test4,test1也变化
test3.__proto__.e = 233;
// 其实就相当于在 Object.prototype 上挂载了 e
// 所以 test1、test2、test4 的原型上都会有 e
const v1 = 123;
const v2 = '123';
const v3 = true;
const v4 = function test() {};
const v5 = Object.assign({}, v1, v2, v3, v4);
console.log(v5);
关键点:
const r1 = new Number(123);
const r2 = new String('123');
const r3 = new Boolean(true);
const r4 = new Function(function test() {});
console.log({
r1, r2, r3, r4
});
[r1, r2, r3, r4].forEach(item => {
for (var key in item) {
console.log(key, item[key]);
}
});
发现只有字符串的包装对象才可能有自身可枚举属性
https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Object/assign
Object.prototype.assign = function(target, ...sources) {
if (target == undefined) {
return new TypeError('Cannot convert undefined or null to object');
}
let to = Object(target); // 对象化
sources.forEach(source => {
for (key in source) {
if (Object.prototype.hasOwnProperty.call(source, key)) {
to[key] = source[key];
}
}
});
return to;
}
Object.prototype.myAssign = function(target, ...sources) {
if (target == undefined) {
return new TypeError('Cannot convert undefined or null to object');
}
let to = Object(target); // 对象化
let descriptors = [];
sources.forEach(source => {
Object.keys(source).reduce((pre, cur) => {
return descriptors[cur] = Object.getOwnPropertyDescriptor(source, cur);
}, descriptors);
});
Object.defineProperties(to, descriptors);
return to;
}
const source = {
a: 1,
get b() {
console.log('get b');
return 2;
}
}
const obj = Object.myAssign({}, source);
console.log(obj);