[关闭]
@TedZhou 2018-12-10T11:55:14.000000Z 字数 1078 阅读 363

JS对象的克隆Clone

javascript


浅克隆[Plain Clone]:

  1. var obj1 = {foo: "foo", bar: "bar"};
  2. var obj2 = {foo: "foo2", bar: "bar2"};
  3. var copy1 = {...obj1}; // Object {foo: "foo", bar: "bar"}
  4. var copy2 = Object.assign({}, obj); //Object {foo: "foo2", bar: "bar2"}
  5. var copySpread = {...obj1, ...obj2}; //Object {foo: "foo2", bar: "bar2"}
  6. var copyAssign = Object.assign({}, obj2, obj1); //Object {foo: "foo", bar: "bar"}

JSON克隆[Json Clone]

  1. var obj = { a: 0, b: { c: 0 } };
  2. var copy = JSON.parse(JSON.stringify(obj));

深度克隆[Deep Clone]

  1. function deepClone(obj) {
  2. var copy;
  3. // Handle the 3 simple types, and null or undefined
  4. if (null == obj || "object" != typeof obj) return obj;
  5. // Handle Date
  6. if (obj instanceof Date) {
  7. copy = new Date();
  8. copy.setTime(obj.getTime());
  9. return copy;
  10. }
  11. // Handle Array
  12. if (obj instanceof Array) {
  13. copy = [];
  14. for (var i = 0, len = obj.length; i < len; i++) {
  15. copy[i] = deepClone(obj[i]);
  16. }
  17. return copy;
  18. }
  19. // Handle Function
  20. if (obj instanceof Function) {
  21. copy = function() {
  22. return obj.apply(this, arguments);
  23. }
  24. return copy;
  25. }
  26. // Handle Object
  27. if (obj instanceof Object) {
  28. copy = {};
  29. for (var attr in obj) {
  30. if (obj.hasOwnProperty(attr)) copy[attr] = deepClone(obj[attr]);
  31. }
  32. return copy;
  33. }
  34. throw new Error("Unable to copy obj as type isn't supported " + obj.constructor.name);
  35. }
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注