Pass by value and pass by reference

Source: Internet
Author: User

Parameters of all functions in ecmascept are passed by value. That is to say, copying the value outside the function to the parameter inside the function is the same as copying the value from one variable to another.

When you pass a value of the basic type to a parameter, the passed value is copied to a local variable (an element in the parameter, arguments object ). When a value of the reference type is passed, the address of the value in the memory is copied to a local variable. Therefore, changes to the local variable are reflected outside the function.

JavaScript code:

Function addten (Num ){

Num + = 10;

Return num;

}

VaR COUNT = 10;

VaR result = addten (count );

Aelrt (count); // 20, unchanged

Aelrt (result); // 30

 

JavaScript code:

Function setname (OBJ ){

OBJ. Name = "Nicolas ";

}

VaR person = new object ();

Setname (person );

Alert (person. Name); // Nicolas

In the above Code, create an object and save it in the variable person. Then the object is passed to the setname () function and copied to OBJ.

In this function, OBJ and person reference the same object.

If the person is passed by reference, the person will be automatically changed to a new object pointing to its name attribute "gred. However, when you access person. name again, the displayed value is still "Nicolas ".

JavaScript code:

Function setname (OBJ ){

OBJ. Name = "Nicolas ";

OBJ = new object ();

OBJ. Name = "Greg ";

}

VaR person = new object ();

Setname (person );

Alert (person. Name); // Greg (from JavaScript advanced programming)

If this is passed by value, why is the following code passed by reference? Answers from experts

VaR obj1 = new object ();

VaR obj2 = obj1;

Obj1.name = "Nicolas ";

Alert (obj2.name); // Nicolas

Obj1 = new object ();

Obj1.name = "Greg ";

Alert (obj2.name); // Nicolas

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.