Deep understanding of object copying in JavaScript (objects clone) _ Basics

Source: Internet
Author: User
Tags extend hasownproperty

JavaScript does not directly provide a method for object replication (the object clone). So when you change object B in the following code, you change object A.

A = {k1:1, k2:2, k3:3};

b = A;

B.K2 = 4;

If you just want to change B and keep a unchanged, you need to copy object A.

Using jquery for Object replication

With jquery, the Extend method of jquery can be used to replicate objects.

A = {k1:1, k2:2, k3:3};

b = {};

$.extend (B,a);

Customizing the Clone () method to implement object replication

The following method is the basic idea of object replication.

Object.prototype.clone = function () {
 var copy = (this instanceof Array)? [] : {};
 For (attr in this) {
  if (!obj.hasownproperty (attr)) continue;
  COPY[ATTR] = (typeof this[i] = = "Object")? Obj[attr].clone (): obj[attr];
 } 
 return copy;


A = {k1:1, k2:2, k3:3};
b = A.clone ();

The following example is considered more comprehensive and is suitable for deep replication of most objects (Deep copy).

function Clone (obj) {
  //Handle The 3 simple types, and null or undefined
  if (null = obj | | "Object"!= typeof obj) return to obj;

  Handle Date
  if (obj instanceof date) {
    var copy = new Date ();
    Copy.settime (Obj.gettime ());
    return copy;
  }

  Handle array
  if (obj instanceof array) {
    var copy = [];
    for (var i = 0, var len = Obj.length i < len; ++i) {
      Copy[i] = Clone (obj[i));
    return copy;
  }

  Handle Object
  if (obj instanceof object) {
    var copy = {};
    for (var attr in obj) {
      if (Obj.hasownproperty (attr)) copy[attr] = Clone (obj[attr));
    return copy;
  }

  throw new Error ("Unable to copy obj! Its type isn ' t supported. ');

The above in-depth understanding of the object of JavaScript in the replication of objects (object Clone) is a small series to share all the content, hope to give you a reference, but also hope that we support the cloud habitat community.

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.