tags:

views:

509

answers:

4

is it possibile in javascript to assign an alias/refrence 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 possibile to alias arguments.callee in this code?:

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

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
Darin Dimitrov
that was fast =) i want to make an alias to arguments.callee inside my function (just to avoid typing arguments.callee every time). is this possibile with this method ? If I understand, I can alias "arguments" but I still have to write "callee" anyway, isn't it ?
gpilotino
could you post your code?
Darin Dimitrov
posted. i accept this answer as my question was too generic.
gpilotino
@Darin: this is a bit oversimplifying it. It's immutable vs mutable types, rather than primitive types vs objects. In JavaScript everything is an object in some form.
Crescent Fresh
+1  A: 

Hi,

edit to my previous answer: if you want to count a function's invocations, you might want to try:

var countMe = ( function() {
  var c = 0;

  return function() {
    c++;
    return c;
  }
})();

alert(countMe()); // Alerts "1"
alert(countMe()); // Alerts "2"

Here, c serves as the counter, and you do not have to use arguments.callee.

Cheers Tom

Tom Bartel
+1  A: 

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
stereofrog
+1  A: 

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.

Justin Love
thank you, that's what i needed to know.
gpilotino