Why does this return 'foo', not 'foobar'? I need function g to modify (non-global) var v, yet function g is a global function. Thanks.
f();
function f() {
var v = 'foo';
g(v);
alert(v);
}
function g(v) {
v = v+'bar';
return v;
}
Because you return v from g(v) call but you do not reassign v
f();
function f() {
var v = 'foo';
v = g(v); //you need to assign what is returned
alert(v);
}
function g(v) {
v = v+'bar';
return v;
}
Because javascript only works by value, not by reference. See John Hartsock's answer.
Primitive
ALL arguments in javascript (the string argument to g, in this case) are pass-by-value instead of pass-by-reference, which means the v
you're working with in function g(v) is a copy of the v
in function f.
Edit:
all arguments are passed by value, not just primitives.
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.