Javascript does not have support for passing by reference (although objects are passed by reference and this link is maintained until it is overwritten by the assignment, for example, using = ), but you can simulate the ref C # keyword using the following method:
function test(obj) { obj.Value = {}; //obj.Value = {name:"changed"}; } var my_obj = { name: 'foo' }; (function () { my_obj = {Value: my_obj}; var $return = test(my_obj); my_obj = my_obj.Value; return $return; }).call(this); alert(my_obj.name); // undefined, as expected // In the question this returns "foo" because // assignment causes dereference
Of course, you can use global functions and the call function without arguments, in which case the links are not skipped as follows:
var obj = { name: 'foo' }; function test() { obj = {}; } test(); alert(obj.name);
If you have all the code in closure, then everything is simpler and higher, as global global namespaces do not pollute:
(function(){ var obj = { name: 'foo' }; function test() { obj = {}; } test(); alert(obj.name);
The aforementioned “globals inside closure” technique is good if you need to port some C # code with ref arguments to Javascript. For example. The following C # code:
void MainLoop() { // ... MyStruct pt1 = CreateMyStruct(1); MyStruct pt2 = CreateMyStruct(2); SwapPoints(ref pt1, ref pt2); // ... } void SwapPoints(ref MyStruct pt1, ref MyStruct pt2) { MyStruct tmp = pt1; pt1 = pt2; pt2 = tmp; }
can be ported to javascript using something like:
(function(){ var pt1, pt2; function CreateMyStruct(myvar) { return {"myvar":myvar} } function MainLoop() {
or if you need to use local variables and function arguments, then the solution can be based on the first example of my answer as follows:
(function(){ function CreateMyStruct(myvar) { return {"myvar":myvar} } function MainLoop() {
Indeed, I must say that Javascript is not enough when it does not have a native ref ! The code will be much simpler.