Deep copy using JavaScript

Source: Internet
Author: User

Deep copy using JavaScript


The reason for writing this series is that I encountered a set of good questions on the internet, involving all the corners of the front-end, as well as modularization, HTTP, and backend. Question at the front end

First, let's discuss about how to implement deep copy in JS.

 
 
  1. var obj = { a: 1 };
  2. var obj2 = obj;

  3. obj2.a = 3;
  4. obj.a; // 3

This is a simple object reference. This simply copies the object reference address to the variable obj2, instead of cloning the real object, there is still only one original object. The impact is that when I modify the internal properties of obj2 or add new properties, obj will be affected because the values of the two variables are the address reference of the same object, that is, the two point to the same object.

This is the meaning of the so-called deep copy. instead of copying the reference address, it is actually copying a new object. At present, the standard does not provide a similar native method (mainly because the demand is not big, JS itself can handle well ). Therefore, for deep copy, the main problem is the replication of arrays, objects, and methods.


Objects: Generally, the attributes of objects on the prototype chain are all traversed and used by for in. Because of the diversity of browsers, hasOwnPrototype needs to be used for filtering. Of course, you also need to consider the situation where a property value is an object, array, function, etc.

Array: for an array, it can be traversed in a loop like an object. However, the length is usually used for loop and the empty array is continuously pushed.

Function: for general databases, some deep copy functions are basically not processed. Actually, you can call the toString of the Function and then use eval or Function for processing to obtain a new Function.

The last instance is a simple copy method mix in the database you are writing. Some functions are extended due to library reasons and the methods are not replicated, an external method type is used to determine the type, such as array object function.


  1. /** Object extension mix
  2. *
  3. * @ Method mix does not extend the prototype attributes
  4. * @ Param {obj} the target object that the consumer er can expand to the peripheral object if no target object exists.
  5. * @ Param {obj} obj: object data to be extended to the target object
  6. * @ Param {boolean} ride (optional) Specifies whether to overwrite the original object property. The default value is true.
  7. * @ Param {boolean} deep (optional) Specifies whether simple deep copy is required. The default value is false.
  8. *
  9. * @ Return {Object} returns the target Object
  10. *
  11. */
  12. VarhasOwn = Object. prototype. hasOwnProperty;
  13. Function mix (explorer, obj ){
  14. Var args = []. slice. call (arguments), key, I = 1, deep, ride, value, valueType;

  15. If (typeof args [args. length-2] === "boolean "){
  16. Deep = args. pop ();
  17. Ride = args. pop ();
  18. } Else {
  19. Ride = (typeof args [args. length-1] = "boolean ")? Args. pop (): true;
  20. Deep = false;
  21. If (args. length <2 ){
  22. Cycler = (this! = Global )? This :{};
  23. If (args. length = 0 ){
  24. Return aggreger;
  25. }
  26. }
  27. }

  28. While (obj = args [I ++]) {
  29. For (key in obj ){
  30. If (hasOwn. call (obj, key )){
  31. If (ride |! (Key in counter ER )){
  32. Value = obj [key];
  33. ValueType = type (value );
  34. If (deep & (valueType === "object ")){
  35. Aggreger [key] = {};
  36. Mix (Cycler [key], value, ride, deep );
  37. } Else if (deep & (valueType === "array ")){
  38. Aggreger [key] = [];
  39. Mix (Cycler [key], value, ride, deep );
  40. } Else {
  41. Aggreger [key] = obj [key];
  42. }
  43. }
  44. }
  45. }
  46. }
  47. Return aggreger;
  48. }


For the type function, the source code is as follows:

 
 
  1. // Type determination object
  2. Var class2type = {
  3. "[ObjectHTMLDocument]": "document ",
  4. "[ObjectHTMLCollection]": "nodeList ",
  5. "[ObjectStaticNodeList]": "nodeList ",
  6. "[ObjectIXMLDOMNodeList]": "nodeList ",
  7. "Null": "null ",
  8. "NaN": "NaN ",
  9. "Undefined": "undefined"
  10. };

  11. "Boolean, Number, String, Function, Array, Date, RegExp, Document, Arguments, NodeList"
  12. . Replace (/[^,] +/g, function (type ){
  13. Class2type ["[object" + type + "]"] = type. toLowerCase ();
  14. });

  15. // Type determination
  16. Function type (obj, isType ){
  17. Var key = (obj = null | obj! = Obj )? Obj + "": Object. prototype. toString. call (obj )),
  18. Result;

  19. If (typeof (result = class2type [key])! = "String "){
  20. If (obj. nodeType = 9 ){
  21. Result = class2type ["Document"];
  22. } Else if (obj. item & typeof obj. length = "number "){
  23. Result = class2type ["NodeList"];
  24. } Else {
  25. Result = key. slice (8,-1 );
  26. }
  27. }


  28. If (isType ){
  29. Return result = isType. toLowerCase;
  30. }


  31. Return result;
  32. }


This is a simple example of deep copy in Javascript. If you have any errors, please note.







Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.