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");");
Like Seth's answer, but uses
Object.keys()
instead:However, I think you should do like "karim79"
In ES6, you could write something like:
Not really the best looking thing, but it gets the job done.
This leverages ES6's object destructuring.
More info here: https://hacks.mozilla.org/2015/05/es6-in-depth-destructuring/
No, there is not.
Besides, if you can write
variablesName(myFirstName)
, you already know the variable name ("myFirstName").This works for basic expressions
Example
Snippet:
You can reflect on types in javascript and get the name of properties and methods but what you need is sth like
Lambda Expressions Trees
in .NET, I think it's not be possible due to dynamic nature and lack of static type system in javascript.