views:

722

answers:

4

Is it possible to find the memory address of a JavaScript variable? The JavaScript code is part of (embedded into) a normal application where JavaScript is used as a front end to C++ and does not run on the browser. The JavaScript implementation used is SpiderMonkey.

A: 

It all will depend on your JS implementation like V8, etc. What are you using?

Daniel A. White
+5  A: 

If it would be possible at all, it would be very dependent on the javascript engine. The more modern javascript engine compile their code using a just in time compiler and messing with their internal variables would be either bad for performance, or bad for stability.

If the engine allows it, why not make a function call interface to some native code to exchange the variable's values?

Emiel
Yes I agree, think need to have some code in C++ which can interface with JavaScript.
vivekian2
+1  A: 

Very good question with no good answer so far... I'm disappointed.

Address of a variable can be treated as its unique identifier. Being able to see such an address would help with debugging identity problems. It's when you have two or more variables and you expect they all point to the same object but comparing any two of them with === operator returns false. If it were possible to obtain an address of a variable you could track when and where it was created and find out what's going on.

Piotr Dobrogost
A: 

Bit of a grave dig here, but oh well. You can't access a variable's memory address. However you can store the variable name and access the original variable like that.

e.g:

function plusfive(varName)
{
    window[varName] += 5;   // Accesses original variable from the window object
}

var myVariable;
myVariable = 2;
plusfive('myVariable');
document.write(myVariable); // Returns 7

If you really need pointer functionality, you could probably create a class which manages all variables in a similar fashion.

Andrew Dunn