javascript variable reference/alias
Solution 1:
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 aliasToObj = obj;
aliasToObj.x ++;
alert( obj.x ); // displays 2
Solution 2:
To some degree this is possible, you can create an alias to a variable using closures:
Function.prototype.toString = function() {
return this();
}
var x = 1;
var y = function() { return x }
x++;
alert(y); // prints 2, no need for () because of toString redefinition
Solution 3:
Whether you can alias something depends on the data type. Objects, arrays, and functions will be handled by reference and aliasing is possible. Other types are essentially atomic, and the variable stores the value rather than a reference to a value.
arguments.callee is a function, and therefore you can have a reference to it and modify that shared object.
function foo() {
var self = arguments.callee;
self.myStaticVar = self.myStaticVar || 0;
self.myStaticVar++;
return self.myStaticVar;
}
Note that if in the above code you were to say self = function() {return 42;};
then self
would then refer to a different object than arguments.callee
, which remains a reference to foo
. When you have a compound object, the assignment operator replaces the reference, it does not change the referred object. With atomic values, a case like y++
is equivalent to y = y + 1
, which is assigning a 'new' integer to the variable.
Solution 4:
Expanding on user187291's post, you could also use getters/setters to get around having to use functions.
var x = 1;
var ref = {
get x() { return x; },
set x(v) { x = v; }
};
(ref.x)++;
console.log(x); // prints '2'
x--;
console.log(ref.x); // prints '1'