Home >Web Front-end >JS Tutorial >Passing variables in JavaScript: Pass by value? Pass by reference?_javascript tips

Passing variables in JavaScript: Pass by value? Pass by reference?_javascript tips

WBOY
WBOYOriginal
2016-05-16 18:10:31972browse

When variable A is assigned to variable B, the value in the stack will be copied to the space allocated for the new variable.

How to understand?

Copy code The code is as follows:

var x = y = 1;
y = 2;
alert(x);

What is the value of x?
Copy code The code is as follows:

var obj = {};
var sub = {};
sub['id'] = 3;
obj['sub'] = sub;
sub['id'] = 4;
alert(obj['sub'] ['id']);

What is the value of obj['sub']['id']? Do they really meet your expectations?

We ran the two pieces of code respectively and found that the value of x in the first piece of program did not change, but the value of obj['sub']['id'] in the second piece of program changed. It is also an assignment operation, and it is also modifying the value of another copy. Why does the source variable of a section of the program remain unchanged, but the source variable of a section of the program changes? Is this transfer by value or by reference?

The answer is given in "JavaScript Advanced Programming Second Edition" translated by Li Songfeng.
In the first two examples, the value of A is actually copied to B. The difference is that in the first example, the value of A is 1 of type int, while in the second example , the value of A is an address pointer, which can access an object. After copying, the value of B in the first example becomes a new int, and its value is 1, while in the second example B The value becomes the new address pointer, and its value is the address of this object.

The following example can help to understand
Copy the code The code is as follows:

function setName(obj){
obj.name = "test1";
obj = {};
obj.name = "test2";
}
var person = new Object() ;
setName(person);
alert(person.name);

As you can see, although the setName function is called to modify the name attribute of the variable, person.name The value has not changed. This is because in the function, the address pointed to by obj is changed, so modifying the name attribute of this address will not affect the name attribute of the original address. From another aspect, it also confirms that JavaScript is passed by value.
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn