Reputation: 1235
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
console.log("after making null obj",obj2.name);//now this will need to be null but is working why??
i made object (obj) then assigned it to the second object (obj2) and finally make obj null but after that obj2.name showing me "faizan". why? it need to show nothing cause obj null now
Upvotes: 1
Views: 65
Reputation: 399
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
Upvotes: 0
Reputation: 33189
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 = {};
Upvotes: 2