作用

用于将所有可枚举属性的值从一个或多个源对象复制到目标对象。

实例

  1. const a = { a: 1, b: 2 };
  2. const b = { b: 4, c: 5 };
  3. const c = Object.assign(a, b);
  4. console.log(c);
  5. // expected output: Object { a: 1, b: 4, c: 5 }
  6. console.log(a);
  7. // expected output: Object { a: 1, b: 4, c: 5 }
  1. const a = { a: 1, b: 2 };
  2. const b = { b: 4, c: 5 };
  3. const c = Object.assign({},a, b);
  4. console.log(c);
  5. // expected output: Object { a: 1, b: 4, c: 5 }
  6. console.log(a);
  7. // expected output: Object { a: 1, b: 2}

源码实现

  1. function extend(target, source) {
  2. for (var obj in source) {
  3. target[obj] = source[obj];
  4. }
  5. return target;
  6. }
  7. // 测试
  8. var a = {a: 1, b: 2};
  9. var b = {a: 2, b: 3, c: 4};
  10. var c = extend(a, b);
  11. console.log(c); // expected output: Object { a: 2, b: 3,c: 4}