fish potato fish potato - 2 months ago 8
Javascript Question

Variable name as a string in Javascript

Is there a way to get a variable name as a string in Javascript? (like NSStringFromSelector in Cocoa)

I would like to do like this:

var myFirstName = 'John';
alert(variablesName(myFirstName) + ":" + myFirstName);

--> myFirstName:John


-- added

I'm trying to connect a browser and another program using JavaScript. I would like to send instance names from a browser to another program for callback method.

FooClass = function(){};
FooClass.someMethod = function(json) {
// Do something
}

instanceA = new FooClass();
instanceB = new FooClass();
doSomethingInAnotherProcess(instanceB); // result will be substituted by using instanceB.someMethod();


....

[From another program]

evaluateJavascriptInBrowser("(instanceName).someMethod("resultA");");


In PHP:
How to get a variable name as a string in PHP?

Answer

Typically, you would use a hash table for a situation where you want to map a name to some value, and be able to retrieve both.

var obj = { myFirstName: 'John' };
obj.foo = 'Another name';
for(key in obj)
    alert(key + ': ' + obj[key]);

Try it here.