[turboid] javascript solutions

Home     Contact     Search     About me
Syntax solutions
22 Dec 2011

Passing variables by reference

Is there something like "ByRef" in JavaScript?

Passing variables by reference seems to be impossible in the first moment. And in fact there is no standard possibility to do this, as JavaScript does not offer an equivalent for Visual Basic's ByRef or C's int&.

Unlike standard JavaScript, programming languages like Visual Basic and other languages allow to pass variables to a function by reference instead of passing them by value. That means that any changes a function performs on one of such parameters affects the content of the variable with the same name outside the function, as long as this variable name is used when passing it. Here's an example in Visual Basic Script:

Sub show(ByRef x)
	x = 300
	msgBox myVar
End Sub

myVar = 13
show myVar

In order to try out this code in Windows, you only have to copy it and save it somewhere as "myScript.vbs" and then perform a double click on the icon. What do you get? Surprisingly enough for some of us, you won't get 13, but 300. The reason is that by using Byref you explicitly wanted the function to treat x as if it where myVar. If you replace ByRef with ByVal you would get 13. Could we do the same thing in JavaScript, let's say, this way?

// This won't work:

function show(Byref x){
	x = 300;
	alert(myVar);
}

myVar = 13;
show(myVar);

That does not work that way, and to do such a thing in JavaScript seems to be impossible in the first moment. And in fact there is no standard possibility to do this, as JavaScript does not offer an equivalent for Visual Basic's ByRef. But already in 2007 a Mexican developer who calls himself "sirdarckcat" wrote a very good approach in his blog. I adopted his approach to provide a function called [Object].setByRef() which enables us to use a similar structure as shown in the Visual Basic Script above:

Object.prototype.setByRef = function(val){ // From sirdarckcat.blogspot.com
	this.valueOf=this.toSource=this.toString=function(){
		return val;
	};
	return val;
};

Now you can use almost the same structure as in the Visual Basic Script example:

function show(x){
	x.setByRef(300);
	alert(myVar);
}

myVar = Object(13);
show(myVar);

Unlike in Visual basic Script, this even leaves to you the choice wether treating the passed variable as passed by reference or by value. In the latter case you only have to replace x.setByRef(300) by x = 300.


Comments

Add comment:

Name: (required)
E-Mail: (required, remains invisible)
Website:
Comment:
Please check all (anti-spam):