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");");
this isn't able to be made into a function as it returns the name of the function's variable
Since ECMAScript 5.1 you can use Object.keys to get the names of all properties from an object.
Here is an example:
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.
You can use the following solution to solve your problem:
I needed this, don't want to use objects, and came up with the following solution, turning the question around.
Instead of converting the variable name into a string, I convert a string into a variable.
This only works if the variable name is known of course.
Take this:
This should display:
This can be done like this:
So I use the string
"height"
and turn that into a variableheight
using thewindow[]
command.When having a function write a function that changes different global variables values it is not always myfirstname it is whatever happens to be passing through. Try this worked for me.
Run in jsfiddle
Will write to the window 'jack'.