SoFunction
Updated on 2025-03-03

Deeply understand the value and references in JavaScript

1. Pass the value (by value)

A copy of the value of a variable will have nothing to do with the original value, that is, even if the new value is modified, the original value will not change. In JavaScript, basic types are all passed values.

Copy the codeThe code is as follows:

function testPassValue()
{
   var m=1;
   var n=2;
//Copy a copy of the values ​​of m and n and pass it to passValue
   passValue(m,n);
alert(m); // Will be the original value
}
function passValue(a,b)
{
a = a+b; //Change the value of a, here a is just a copy of the original value
  alert(a); 
}

Output result:
3

1

2. Pass a reference (by reference).

The reference itself copies a copy and passes it to the function. The object pointed to by the reference is not copied and passed (the same is true in Java). In function, if the value of the object's attribute is changed, since it points to the same object as the original reference, the modified value will be accessed through the original reference;

However, if the reference is only pointed to a new object in the function, the value of the original object will not be changed, and the copy of the reference will be changed.

Copy the codeThe code is as follows:

function testPassValue()
{
  var date = new Date(2006,02,27);
alert(());  //The output is 27
//Copy a copy of the date reference itself and pass it to passReference. Note that the object pointed to by date is not copied
  passReference(date);
alert(());  //The output is 12
//Same as above
  changeReference(date);
alert(());  //The output is still 12
}
function passReference(da)
{
// Since da and the original reference point to the same object, outside the function, the date attribute value of the object will be accessed through the original reference, which will be the modified value.
   (12);
}
function changeReference(da)
{
//At this time, the da quote is actually a copy of the original quote. The reference itself will be reassigned and will not affect the original quote.
   da= new Date(2007,05,11);

//Point the da reference to a new object, and the original reference is still pointing to the original object
alert(());     // Output is 11
}


3 Special String

In JavaScript, String is also referenced. There is only the charAt method in js, but there is no corresponding modification method. It is the same as String in Java, and both have invariance.

Copy the codeThe code is as follows:

var s1 = "hello";
var s2 = "hell" + "o";
if (s1 == s2)  
alert("s1 = s2");  // Will this sentence be executed? People who are familiar with java may think that it will not be executed (I have a lot of complaints about this sentence, and it will also be executed in java!), because == in java compares identity. In fact, in js, String== compares whether the values ​​are equal, so this sentence will be executed. However, for other Object == comparisons, it is the same as in java.