Deep understanding of passed values and passed references in JavaScript

  • 2020-03-30 00:46:25
  • OfStack

1. By value

The value of the variable is copied out of the original value, which means that even if the new value is modified, the original value will not change. In JavaScript, basic types are passed values.


function testPassValue()
{
   var m=1;
   var n=2;
   //Copy the value of m,n and pass it to passValue
   passValue(m,n);
   alert(m);  //It's going to be the original value
}
function passValue(a,b)
{
  a = a+b; //Change the value of a, where a is just a copy of the original value
  alert(a);  
}

Output results:
3

1

2. By reference.

The reference itself is copied to the function, and the object to which the reference refers is not copied and passed (the same is true in Java). In function, if the value of the attribute of the object is changed, since the original reference refers to the same object, the modified value will be accessed through the original reference.

However, if you simply point a reference to a new object in function, you will not change the value of the original object, only the copied reference.


function testPassValue()
{
  var date = new Date(2006,02,27);
  alert(date.getDate());  //The output of 27
  //Make a copy of the date reference itself and pass it to passReference, noting that the object to which the date refers is not copied
  passReference(date);
  alert(date.getDate());  //The output of 12
  // Same as above 
  changeReference(date);
  alert(date.getDate());  //The output is also 12
}
function passReference(da)
{
 //Since da and the original reference point to the same object, outside of function, the date attribute value of the object will be accessed through the original reference, which will be the modified value.
   da.setDate(12); 
}
function changeReference(da)
{
   //At this point, the da reference is actually a copy of the original reference, and reassigning the reference itself will not affect the original reference
   da= new Date(2007,05,11); 
//Point the da reference to a new object, where the original reference points to the same object
   alert(da.getDate());     //The output of 11
}

3. Special String 

In JavaScript,String also refers to the.js method with only charAt, but no corresponding modification method, which is the same as String in Java and has invariability.


var s1 = "hello";
var s2 = "hell" + "o";
if (s1 == s2)   
alert("s1 = s2");  //Will this sentence be executed? Those familiar with Java might think it won't be executed (which I hate to say, but it will be executed in Java too!). In fact, String== in js is compared to whether the values are equal or not, so this sentence will be executed.


Related articles: