From what I understand, pass-by-reference in JS terminology means pass-by-pointer in C++ terminology, and JS doesn't have pass-by-reference in C++ terminology - and there is lot of confusion about this, because the two worlds rarely communicate: the C++ and the JS programs usually covers completely different realms.
For example, JS terminology describes pointers as copy of object reference (which doesn't make sense in C++ terminology where reference means alias). And when JS community says everything is passed by value it means the value of the pointer (primitives are boxed when passed).
There is a way to make the function1 get the updated value from myVar, though. It can be done by call-by-name in the following steps:
- create a context in
function1
- create
myVar
in the context
- call the
function2
in the created context and pass the name
The essence of pass-by-reference equivalent implemented as pass-by-name below is the line
function2.call(context, "myVar");
and the reference in function2
is obtained by
this[name]
as demonstrated in the code below
function1 = function() {
var context = {};
context.myVar = {1:"one", 2:"two"};
console.log("function1 before:", context.myVar[1]);
function2.call(context, "myVar");
console.log("function1 after:", context.myVar[1]);
}
function2 = function(name) {
console.log("function2 before", this[name][1]);
this[name] = {1:"three", 2:"nine"};
console.log("function2 after", this[name][1]);
}
function1();