MDN之Web 开发技术【Object.assign()】

ゞ 浴缸里的玫瑰 2021-07-05 01:05 539阅读 0赞

Object.assign() 方法用于将所有可枚举属性的值从一个或多个源对象复制到目标对象。它将返回目标对象。
在这里插入图片描述

语法

  1. Object.assign(target, ...sources)

参数

target
目标对象。
sources
源对象。

返回值

目标对象。

描述

如果目标对象中的属性具有相同的键,则属性将被源对象中的属性覆盖。后面的源对象的属性将类似地覆盖前面的源对象的属性。

Object.assign 方法只会拷贝源对象自身的并且可枚举的属性到目标对象。该方法使用源对象的[[Get]]和目标对象的[[Set]],所以它会调用相关 gettersetter。因此,它分配属性,而不仅仅是复制或定义新的属性。如果合并源包含getter,这可能使其不适合将新属性合并到原型中。为了将属性定义(包括其可枚举性)复制到原型,应使用Object.getOwnPropertyDescriptor()Object.defineProperty()

String类型和 Symbol 类型的属性都会被拷贝。

在出现错误的情况下,例如,如果属性不可写,会引发TypeError,如果在引发错误之前添加了任何属性,则可以更改target对象。

注意,Object.assign 不会在那些source对象值为 nullundefined 的时候抛出错误。

Polyfill

这个 polyfill 不支持 symbol 属性, 由于 ES5 中本来就不存在 symbols :

  1. if (typeof Object.assign !== 'function') {
  2. // Must be writable: true, enumerable: false, configurable: true
  3. Object.defineProperty(Object, "assign", {
  4. value: function assign(target, varArgs) { // .length of function is 2
  5. 'use strict';
  6. if (target === null || target === undefined) {
  7. throw new TypeError('Cannot convert undefined or null to object');
  8. }
  9. var to = Object(target);
  10. for (var index = 1; index < arguments.length; index++) {
  11. var nextSource = arguments[index];
  12. if (nextSource !== null && nextSource !== undefined) {
  13. for (var nextKey in nextSource) {
  14. // Avoid bugs when hasOwnProperty is shadowed
  15. if (Object.prototype.hasOwnProperty.call(nextSource, nextKey)) {
  16. to[nextKey] = nextSource[nextKey];
  17. }
  18. }
  19. }
  20. }
  21. return to;
  22. },
  23. writable: true,
  24. configurable: true
  25. });
  26. }

示例

复制一个对象

  1. const obj = { a: 1 };
  2. const copy = Object.assign({ }, obj);
  3. console.log(copy); // { a: 1 }

深拷贝问题

针对深拷贝,需要使用其他办法,因为 Object.assign()拷贝的是(可枚举)属性值。

假如源值是一个对象的引用,它仅仅会复制其引用值。

  1. const log = console.log;
  2. function test() {
  3. 'use strict';
  4. let obj1 = { a: 0 , b: { c: 0}};
  5. let obj2 = Object.assign({ }, obj1);
  6. log(JSON.stringify(obj2));
  7. // { a: 0, b: { c: 0}}
  8. obj1.a = 1;
  9. log(JSON.stringify(obj1));
  10. // { a: 1, b: { c: 0}}
  11. log(JSON.stringify(obj2));
  12. // { a: 0, b: { c: 0}}
  13. obj2.a = 2;
  14. log(JSON.stringify(obj1));
  15. // { a: 1, b: { c: 0}}
  16. log(JSON.stringify(obj2));
  17. // { a: 2, b: { c: 0}}
  18. obj2.b.c = 3;
  19. log(JSON.stringify(obj1));
  20. // { a: 1, b: { c: 3}}
  21. log(JSON.stringify(obj2));
  22. // { a: 2, b: { c: 3}}
  23. // Deep Clone
  24. obj1 = { a: 0 , b: { c: 0}};
  25. let obj3 = JSON.parse(JSON.stringify(obj1));
  26. obj1.a = 4;
  27. obj1.b.c = 4;
  28. log(JSON.stringify(obj3));
  29. // { a: 0, b: { c: 0}}
  30. }
  31. ​​​​​​​test();

合并对象

  1. const o1 = { a: 1 };
  2. const o2 = { b: 2 };
  3. const o3 = { c: 3 };
  4. const obj = Object.assign(o1, o2, o3);
  5. console.log(obj); // { a: 1, b: 2, c: 3 }
  6. console.log(o1); // { a: 1, b: 2, c: 3 }, 注意目标对象自身也会改变。

合并具有相同属性的对象

  1. const o1 = { a: 1, b: 1, c: 1 };
  2. const o2 = { b: 2, c: 2 };
  3. const o3 = { c: 3 };
  4. const obj = Object.assign({ }, o1, o2, o3);
  5. console.log(obj); // { a: 1, b: 2, c: 3 }

属性被后续参数中具有相同属性的其他对象覆盖。

拷贝 symbol 类型的属性

  1. const o1 = { a: 1 };
  2. const o2 = { [Symbol('foo')]: 2 };
  3. const obj = Object.assign({ }, o1, o2);
  4. console.log(obj); // { a : 1, [Symbol("foo")]: 2 } (cf. bug 1207182 on Firefox)
  5. Object.getOwnPropertySymbols(obj); // [Symbol(foo)]

继承属性和不可枚举属性是不能拷贝的

  1. const obj = Object.create({ foo: 1}, { // foo 是个继承属性。
  2. bar: {
  3. value: 2 // bar 是个不可枚举属性。
  4. },
  5. baz: {
  6. value: 3,
  7. enumerable: true // baz 是个自身可枚举属性。
  8. }
  9. });
  10. const copy = Object.assign({ }, obj);
  11. console.log(copy); // { baz: 3 }

原始类型会被包装为对象

  1. const v1 = "abc";
  2. const v2 = true;
  3. const v3 = 10;
  4. const v4 = Symbol("foo")
  5. const obj = Object.assign({ }, v1, null, v2, undefined, v3, v4);
  6. // 原始类型会被包装,null 和 undefined 会被忽略。
  7. // 注意,只有字符串的包装对象才可能有自身可枚举属性。
  8. console.log(obj); // { "0": "a", "1": "b", "2": "c" }

异常会打断后续拷贝任务

  1. const target = Object.defineProperty({ }, "foo", {
  2. value: 1,
  3. writable: false
  4. }); // target 的 foo 属性是个只读属性。
  5. Object.assign(target, { bar: 2}, { foo2: 3, foo: 3, foo3: 3}, { baz: 4});
  6. // TypeError: "foo" is read-only
  7. // 注意这个异常是在拷贝第二个源对象的第二个属性时发生的。
  8. console.log(target.bar); // 2,说明第一个源对象拷贝成功了。
  9. console.log(target.foo2); // 3,说明第二个源对象的第一个属性也拷贝成功了。
  10. console.log(target.foo); // 1,只读属性不能被覆盖,所以第二个源对象的第二个属性拷贝失败了。
  11. console.log(target.foo3); // undefined,异常之后 assign 方法就退出了,第三个属性是不会被拷贝到的。
  12. console.log(target.baz); // undefined,第三个源对象更是不会被拷贝到的。

拷贝访问器

  1. const obj = {
  2. foo: 1,
  3. get bar() {
  4. return 2;
  5. }
  6. };
  7. let copy = Object.assign({ }, obj);
  8. console.log(copy); // { foo: 1, bar: 2 } copy.bar的值来自obj.bar的getter函数的返回值
  9. // 下面这个函数会拷贝所有自有属性的属性描述符
  10. function completeAssign(target, ...sources) {
  11. sources.forEach(source => {
  12. let descriptors = Object.keys(source).reduce((descriptors, key) => {
  13. descriptors[key] = Object.getOwnPropertyDescriptor(source, key);
  14. return descriptors;
  15. }, { });
  16. // Object.assign 默认也会拷贝可枚举的Symbols
  17. Object.getOwnPropertySymbols(source).forEach(sym => {
  18. let descriptor = Object.getOwnPropertyDescriptor(source, sym);
  19. if (descriptor.enumerable) {
  20. descriptors[sym] = descriptor;
  21. }
  22. });
  23. Object.defineProperties(target, descriptors);
  24. });
  25. return target;
  26. }
  27. copy = completeAssign({ }, obj);
  28. console.log(copy);
  29. // { foo:1, get bar() { return 2 } }

Polyfill

polyfill不支持 symbol 属性,因为ES5 中根本没有 symbol

  1. if (typeof Object.assign != 'function') {
  2. // Must be writable: true, enumerable: false, configurable: true
  3. Object.defineProperty(Object, "assign", {
  4. value: function assign(target, varArgs) { // .length of function is 2
  5. 'use strict';
  6. if (target == null) { // TypeError if undefined or null
  7. throw new TypeError('Cannot convert undefined or null to object');
  8. }
  9. let to = Object(target);
  10. for (var index = 1; index < arguments.length; index++) {
  11. var nextSource = arguments[index];
  12. if (nextSource != null) { // Skip over if undefined or null
  13. for (let nextKey in nextSource) {
  14. // Avoid bugs when hasOwnProperty is shadowed
  15. if (Object.prototype.hasOwnProperty.call(nextSource, nextKey)) {
  16. to[nextKey] = nextSource[nextKey];
  17. }
  18. }
  19. }
  20. }
  21. return to;
  22. },
  23. writable: true,
  24. configurable: true
  25. });
  26. }

发表评论

表情:
评论列表 (有 0 条评论,539人围观)

还没有评论,来说两句吧...

相关阅读