简体   繁体   中英

Modify global variable inside function via parameter

Here is an example:

 let wish = 'Happy birthday!'; function translate(msg) { msg = 'Alles Gute zum Geburtstag!'; } translate(wish); console.log(wish); 

I realize that it won't modify wish because JavaScript is "pass by value" and not "pass by reference", so how can I modify that variable (which is outside of the function) by passing a value to the function? Is it impossible without changing wish to an object or array to hold my string instead of a primitive?

Instead of a global variable, use an object.

 let wish = { msg: 'Happy birthday!' }; function translate(obj) { obj.msg = 'Alles Gute zum Geburtstag!'; } translate(wish); console.log(wish.msg); 

let wish = 'Happy birthday!';

function translate(msg) {
   msg = 'Alles Gute zum Geburtstag!';
   return wish=msg;
}

translate(wish);
console.log(wish); //Alles Gute zum Geburtstag!

You don't have to use the return, but global variables can be set form anywhere where there isn't a var by the same name in a lesser scope.

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