All, Say we have the code like below.
var b ={};
var a=b;
b=null;
if (a==null)
{
alert('a is null');
}
Before the code running, I had thought the a should be null, because I thought a and b are pointing to same object or they are supposed to be the same address. but it is not . Isn't javascript object reference type like classical language (c++/c#/java)? Or did I miss something important? Thanks.
In JavaScript, all variables are held -- and passed -- by value.
However, in the case of objects (anything not a primitive) that value is a reference.
var v1, v2;
v1 = {
someProp: true
}; // Creates an object
v2 = v1; // The object now has two references pointed to it.
v1 = null; // The object now has one reference.
console.log(v2); // See the value of the object.
v2 = null; // No references left to the object. It can now be garbage collected.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With