导航


HTML

CSS

JavaScript

浏览器 & 网络

版本管理

框架

构建工具

TypeScript

性能优化

软实力

算法

UI、组件库

Node

冷门技能

⭐️ Object.assign(target, source1, source2, ...)

⭐️ 特点

典型案例

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也变化

Untitled

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);

Untitled

关键点:

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]);
  }
});

Untitled

发现只有字符串的包装对象才可能有自身可枚举属性

⭐️ 更多案例

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;
}

自定义 myAssign,同时拷贝 descriptor 属性描述符

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);

Untitled