Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is all javascript object reference type?

Tags:

javascript

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.

like image 972
Joe.wang Avatar asked Jan 28 '26 05:01

Joe.wang


1 Answers

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.
like image 180
Jeremy J Starcher Avatar answered Jan 29 '26 19:01

Jeremy J Starcher