简体   繁体   中英

Reference data type passing in function in Javascript

I have a question about arguments passing in Javascript, as I know that, for primitive data types, when passing through a function, they got copied by value.

Haw about the reference data types?

As an example, see this code:

var person3 = new Object();
setName(person3);
console.log(person3)
function setName(obj){
  obj.Name = "remon"
}

For whom said that it is duplicate, it is not because I am asking the question from memory perspective and I am new in learning programming and the answers to that questions is so advanced for me.

@MinaShaker well, your experiment shows, that it is copied by reference. We see {Name: 'remon'} in console.

 var person3 = new Object(); setName(person3); console.log(person3) function setName(obj){ obj.Name = "remon" } 

And here, if we 'copy' object before sending it to the function we will get {Name: 'simon'}

 var person3 = { Name: "simon" }; setName(Object.assign({}, person3)); console.log(person3) function setName(obj){ obj.Name = "remon" } 

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