简体   繁体   中英

javascript: modifying second variable modifies first

I was trying to understand some javascript and found some quite unexpected behavior. Not knowing much about this language I wanted to find out what this behavior is called so that I can read about it formally.

Here's an example of the behavior:

var test={'x':2};

var test2=test;

test2.sourceLinks = [];

console.log('test',test);
console.log('test2',test2);

To my amazement, I found that modifying the 2nd variable somehow modifies the first as well. The variable "test" will also have an attribute .sourceLinks = []. Do I understand what's happening correctly, and if so, what's the formal term for this behavior?

I found that the answer to this is covered in How do I correctly clone a JavaScript object? after I posted it, although that covered more than I was asking about.

Behavior is called creating a reference . When variable assigned is an object actually it is not copied, rather the result of assignment is a new reference (pointer) to the object.

This doesn't happen with primitive types:

  • number ,
  • string ,
  • boolean ,
  • null ,
  • undefined .

But happens with all object types:

  • object ,
  • Array ,
  • function .

This difference is significant in javascript. When some value should be passed to another scope and it might be modified there it should be passed be reference.

function main(){
    var x = 1;
    modify(x);
    console.log(x);//x remains 1
}
function modify(arg){
    arg = 10;
}

Whereas when it is passed as a field of an object, it can be modified via reference to an object:

function main(){
    var o = {x : 1};
    modifyObj(o);
    console.log(o);//o.x now equals 10
}
function modifyObj(arg){
    arg.x = 10;
}

It's holding the reference .

When you assign object/array/function to another object/array/function it'll assign reference instead of value.

To overcome this you have to clone it

When declaring a variable in Javascript you are creating an object in memory and the variable in the scope is a pointer to that memory object.

In your example both variables (test and test2) are pointing to the same object. Hence, when you modify the the either variable pointer, it is modifying the same object in memory.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM