Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript variable reference/alias

Tags:

javascript

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; } 
like image 889
gpilotino Avatar asked Nov 06 '09 11:11

gpilotino


People also ask

What is alias variable?

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.

How do you reference a variable in JavaScript?

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.

Does JavaScript 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.

How to set value to a variable in JavaScript?

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.


2 Answers

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 
like image 87
Darin Dimitrov Avatar answered Sep 16 '22 17:09

Darin Dimitrov


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  
like image 34
user187291 Avatar answered Sep 20 '22 17:09

user187291