JavaScript function Pass Parameter

Source: Internet
Author: User

The way of the function in JavaScript is more wonderful;

JavaScript does not pass parameters by reference, not strictly all by value, but for reference types, the individual feels like a shared pass

The base type is passed into the function as a parameter (just copy the value to a local variable inside the function)

var a = 10;

function foo (a) {

A = 20;

return A;

}

Console.log (foo (a)); 20

Console.log (a); 10

For a primitive type it is simply a local variable that assigns a value to the inside of the function, so the value modified in the local scope is not reflected in the global variable, and when we look at the reference type here, many people will misunderstand the next generation code.

var obj = {

Name: "ZP"

};

function foo (obj) {

Obj.name = "Zpy";

return obj;

}

Foo (obj);

Console.log (Obj.name); "Zpy"

Many people think that this example is not the local scope of the modified value and reflected in the global variable (so that there is said JS in the conclusion by reference), but in fact it is not so, in JavaScript object name can also be understood as a pointer, when the reference type as a parameter to pass the function, The address is also copied to the local variables inside the function, which means that the local variable of the function and the global variable obj point to the same object in the heap memory.

Look at the following section of the code can be explained that JS is not passed by reference

var obj = {

Name: "ZP"

};

function foo (obj) {

obj = new Object ();

Obj.name = "Zpy";

return obj;

}

Foo (obj);

Console.log (Obj.name); "ZP"

obj = new Object () the address name in the local variable is changed, the local variable is destroyed after the function is executed, so it can be confirmed that JS is not passed by reference


This article is from the "zp1996" blog, make sure to keep this source http://9865481.blog.51cto.com/9855481/1687693

JavaScript function Pass Parameter

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.