Skip to content Skip to sidebar Skip to footer

A Object Property Value Is Showing While The Other Refrence Object Is Null

var obj={name: 'faizan'} var obj2= obj;//obj2 pointing to the same memoray location of obj console.log('before making null obj',obj2.name); obj={}; //obj became null

Solution 1:

The way you believe it to work is incorrect. The second time you set obj = {}; you aren't nullifying the original object. You are instead creating an entirely new empty object, while obj2 still references the original.

You could achieve what you think by using a parent container:

var obj = { container: { name: 'faizan' } };
var obj2 = obj;
obj.container = {};

Solution 2:

as you say :

obj={};

this way just refer the obj to a new reference in the heap , and the content

{name: "faizan"}

exsits in the heap as before , and obj2 is refer the {name: "faizan"} in the heap now .

if you want to deep copy obj to obj2 , just like this :

function copy(o){
  var copy = Object.create( Object.getPrototypeOf(o) );
  var propNames = Object.getOwnPropertyNames(o);

  propNames.forEach(function(name){
    var desc = Object.getOwnPropertyDescriptor(o, name);
    Object.defineProperty(copy, name, desc);
  });

  return copy;
}

var obj={name: "faizan"}
var obj2 = copy(obj);

and then take obj refer null

obj = null

the GC will recycle obj automatically


Post a Comment for "A Object Property Value Is Showing While The Other Refrence Object Is Null"