gpilotino gpilotino - 1 month ago 22
Javascript Question

javascript variable reference/alias

Is it possible in javascript to assign an alias/reference to a local var someway?

I mean something C-like:

function foo() {
var x = 1;
var y = &x;
y++;
alert(x); // prints 2
}


= EDIT =

Is it possible to alias arguments.callee in this code?:

function foo() {
arguments.callee.myStaticVar = arguments.callee.myStaticVar || 0;
arguments.callee.myStaticVar++;
return arguments.callee.myStaticVar;
}

Answer

In javascript primitive types such as integers and strings are passed by value whereas objects are passed by reference. So in order to achieve this you need to use an object:

// declare an object with property x
var obj = { x: 1 };
var anotherObj = obj;
anotherObj.x++;
alert(obj.x); // displays 2