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; }
An alias occurs when different variables point directly or indirectly to a single area of storage. Aliasing refers to assumptions made during optimization about which variables can point to or occupy the same storage area.
In JavaScript, it's just NOT possible to have a reference from one variable to another variable. And, only compound values (Object, Array) can be assigned by reference. Bottom line: The typeof value assigned to a variable decides whether the value is stored with assign-by-value or assign-by-reference.
The Bottom Line on JavaScript References On variable assignment, the scalar primitive values (Number, String, Boolean, undefined, null, Symbol) are assigned-by-value and compound values are assigned-by-reference. The references in JavaScript only point at contained values and NOT at other variables, or references.
You can assign a value to a variable using the = operator when you declare it or after the declaration and before accessing it. In the above example, the msg variable is declared first and then assigned a string value in the next statement.
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With