JS does not pass by address (reference), only by value

Source: Internet
Author: User

Many people, including me, are not completely digested by books. They think that parameters in javascript can be transmitted by values, such as numbers and strings; array and object are passed by address (reference. We should be cautious about this point of view.

VaR
V1 = []
VaR
V2 = {};
VaR
V3 = {};
Function
Foo (V1, V2, V3)
{
V1 = [1];
V2 = [2];
V3 = {A: 3}
}

Foo (V1, V2, V3 );
Alert
(V1); // Blank

Alert
(V2); // [object]

Alert
(V3.a); // undefined

It can be seen that V1, V2, and V3 are not changed, V1 is still an array of zero elements, and V2 and V3 are still blank objects.

However, passing by values such as arrays and objects refers to the value of the variable address.

The passing of values of arrays and objects is different from that of numbers and strings. Numbers and strings directly copy the values, while arrays and objects copy the variable addresses.

After we set V1, V2, and V3 as parameters to the function, we have an address copy. The address copy points to the address copy and the outside V1, V2, and V3
. However, we assigned values for V1, V2, and V3, that is, we changed the point of the address copy and pointed to the new array and object. In this way, internal V1, V2, and V3
And external V1, V2, and V3 are completely disconnected.

If we operate directly without adding a new value, it still operates on the same array or object as V1, V2, and V3.

VaR
V1 = []
VaR
V2 = {};
VaR
V3 = {A: 0 };
Function
Foo (V1, V2, V3)
{
V1.push
(1 );
V2.a = 2;
V3.a = 3;
}

Foo (V1, V2, V3 );
Alert
(V1); // 1

Alert
(V2.a); // 2

Alert
(V3.a); // 3

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.