Tuesday, January 2, 2018

assign object without pointer in javascript

In javascript Clone Object will auto reference to the destination object, because it uses same memory address which points to the reference.

EX :

we have A object with data and clone this in another variable. it set some properties of the instance B has the same result in the original object A:

var A = {a: 25, b: 50, c: 75};
var B = A;
A.a = 30;

console.log("A : ", A.a); //30
console.log("B : ", B.a); //30

If you use  = operator to assign a value to a var with an object on the right side, javascript will not copy but reference the object so you can use Object.create or Object.asign to copy the object not reference

Object.create ()

The Object.create() method creates a new object with the specified prototype object and properties and values.
By using we can create a new object without pointer reference.

EX:

var A = {a: 25, b: 50, c: 75};
var B = Object.create(A);

A.a = 30;

console.log("A : ", A.a); //30
console.log("B : ", B.a); //25

Object.assign()

The Object.assign() method is used to copy the values of all properties from one or more source objects to a target object. It will return the target object's value.

Ex:

var A = {a: 25, b: 50, c: 75};
var B = Object.assign({}, A);

A.a = 30;

console.log("A : ", A.a); //30
console.log("B : ", B.a); //25

You can also use it with nested object

  var A = { a: 50 , b: { c: 30}};
  var B = Object.assign({}, A);
  var C = Object.assign({}, A);

  C.b = Object.assign({}, A.b);

  B.b.c=40;
  C.b.c=60;

  console.log("A : ",  JSON.stringify(A)); // { a: 50, b: { c: 40}}
  console.log("B :", JSON.stringify(B)); // { a: 50, b: { c: 40}}
  console.log("C :", JSON.stringify(C)); // { a: 50, b: { c: 60}}

From the above-nested object if you assign the main object and its property has another nested object then it will create a new object of the parent object only. The nested object will assign a reference to the same memory address.
if you use Object.assign in nested objected same as the parent then it will sore in new memory address and will not point same address so you can copy values and property and methods only.

By using jquery

If you want to preserve the original object, you can do so by passing an empty object as the target.
By using $.extend we can merge the object of two or more objects together into the destination object.

EX :

var myObj1 = {};
myObj1.a = 50;
var myObj2 = $.extend({}, myObj1);

Output :
console.log(myObj1);
console.log(myObj2);

No comments:

Post a Comment