This article mainly introduces the transfer of values and references in JavaScript in detail. If you need them, you can refer to them and hope to help you.
1. Pass the value (by value)
The value of the variable is copied out, which is irrelevant to the original value. That is to say, even if the new value is modified, the original value will not change, in JavaScript, values are basically transmitted.
The Code is as follows:
Function testPassValue ()
{
Var m = 1;
Var n = 2;
// Copy the values of m and n and pass them to passValue.
PassValue (m, n );
Alert (m); // it will be the original value
}
Function passValue (a, B)
{
A = a + B; // change the value of a. Here, a is only a copy of the original value.
Alert ();
}
Output result:
3
1
2. by reference ).
The reference itself copies a copy to the function. The referenced object is not copied and passed (in java). In the function, if the attribute value of the object is changed, because the original reference points to the same object, the accessed value through the original reference will be modified;
However, if you only direct the reference to a new object in the function, the value of the original object will not be changed. All you need to do is copy the reference.
The Code is as follows:
Function testPassValue ()
{
Var date = new Date (2007,02, 27 );
Alert (date. getDate (); // The output is 27
// Copy the date reference and pass it to passReference. Note that the object pointed to by date is not copied.
PassReference (date );
Alert (date. getDate (); // The output is 12
// Same as above
ChangeReference (date );
Alert (date. getDate (); // the output value is also 12.
}
Function passReference (da)
{
// Because da and the original reference point to the same object, outside the function, the date attribute value of the object accessed through the original reference will be the modified value.
Da. setDate (12 );
}
Function changeReference (da)
{
// At this time, the da reference is actually a copy of the original reference, and the reference itself is re-assigned, will not affect the original reference
Da = new Date (2007,05, 11 );
// Point the da reference to a new object. At this time, the original reference still points to the original object.
Alert (da. getDate (); // The output is 11
}
3 Special String
In JavaScript, only the charAt method is passed in referenced. js, but no corresponding modification method. It is the same as the String method in java and has immutability.
The Code is as follows:
Var s1 = "hello ";
Var s2 = "hell" + "o ";
If (s1 = s2)
Alert ("s1 = s2"); // will this sentence be executed? People familiar with java may think that it will not be executed (I am quite a word about this sentence, and it will also be executed in java !), Because the = in java compares the same identity. in fact, in js, String = is compared to whether the values are equal, so this statement will be executed. however, for other objects ==, the comparison is the same as in java.