There is no reference passing in JavaScript, only passing by value

Source: Internet
Author: User

A lot of people, including me, are affected by the incomplete digestion of book knowledge, and think that there are two ways to pass the parameters in JS: numbers, strings, etc. are passed by value; arrays, objects, etc. are passed by address (reference). We have to 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 Object]alert (V3.A); Undefined

thus: v1, V2, V3 have not been changed, V1 is still an array of 0 elements, V2, V3 is still a blank object.

However, arrays, objects, etc. are passed by value, which refers to the value of the variable address.

The pass-by value of arrays, objects, and so on is different from numbers, strings, and so on. numbers, strings are copied directly into the value, and the array, object is to copy the variable address in.

Before we let v1, V2, v3 as parameters into the function, there is a copy of the address, these address copies of the point and the outside of the V1, V2, v3 address point is the same. But we've assigned values for V1, V2, v3, which means we've changed the point of the address copy to a new array and object. Such internal v1, V2, v3 and external v1, V2, v3 are completely broken.

If we do not assign a new value, but instead manipulate it directly, then it is still the same array or object that the outside V1, V2, V3 point to.

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); 1alert (v2.a); 2alert (V3.A); 3

Transferred from: http://www.cftea.com/c/2010/07/TKE282SFVCKL2RLS.asp

There is no reference passing in JavaScript, only passing by value

Related Article

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.