当前位置:首页 > js对象深度克隆

js对象深度克隆

发布于 2周前 阅读 17 次 Javascript
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  6. <title>Document</title>
  7. </head>
  8. <body>
  9. <script>
  10. function A(){
  11. this.name = 'yao';
  12. this.age = '30';
  13. this.say = function () {
  14. return this.name;
  15. }
  16. // console.log(arguments);
  17. }
  18. //A();
  19. // var obj = {
  20. // a: 1,
  21. // b:2,
  22. // c: new Date()
  23. // }
  24. var obj = new A(11);
  25. function deepClone(obj) {
  26. if(obj == null) return null;
  27. if(typeof obj !== 'object') return obj;
  28. if(obj instanceof RegExp) {
  29. return new RegExp(obj);
  30. }
  31. if(obj instanceof Date) {
  32. return new Date(obj);
  33. }
  34. let newObj = new obj.constructor;
  35. for(let key in obj) {
  36. if(obj.hasOwnProperty(key)) {
  37. newObj[key] = deepClone(obj[key]);
  38. }
  39. }
  40. return newObj;
  41. }
  42. let obj2 = deepClone(obj);
  43. console.log(obj, obj2);
  44. console.log(obj.constructor, obj2.constructor);
  45. console.log(obj == obj2);
  46. </script>
  47. </body>
  48. </html>