Learn about parameter passing in javascript again

Source: Internet
Author: User

Parameters of all functions in javascript are passed by value. The following test is performed:

Function addTen (num) {num + = 10; return num;} var count = 20; var result = addTen (count); alert (cont ); // 20 alert (result); // 30
Okay, the above is just a transfer of the basic type. Let's take a look at the transfer of the reference type:

Function setName (obj) {obj. name = "Mark";} var person = new Object (); setName (person); alert (person. name); // Mark
This seems to be a reference transfer, not a value transfer, so let's test again:

Function setName (obj) {obj. name = "Mark"; obj = new Object (); obj. name = "David";} var person = new Object (); setName (person); alert (person. name); // Mark
The only difference between this example and the previous example is that two lines of code are added after the setName () function: one line of code re-defines an object for obj, another line of code defines a name attribute with different values for this object. After the persion is passed to the setName () function, its name attribute is set to Mark, a new object is assigned to obj, and its name attribute is set to David. If the person is passed by reference, the person will be automatically changed to a new object pointing to its name attribute value as David. However, when you access person. name again, the displayed value is still Mark. This indicates that the original reference remains unchanged even if the parameter value is modified within the function. In fact, when you override obj in a function, this variable references a local object. This local object will be destroyed after the function is executed.


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.