Variable Name as a String in Javascript
In Javascript, there is a need to obtain a variable's name as a string. This is similar to the functionality provided by NSStringFromSelector in Cocoa.
To achieve this, one can utilize the following solution:
const myFirstName = 'John' Object.keys({myFirstName})[0]
The above code will return "myFirstName" as the variable name in string format.
This is particularly useful in scenarios like connecting a browser and another program using JavaScript. For instance, in the following example, instance names are sent from a browser to another program for a 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 the other program:
evaluateJavascriptInBrowser("(instanceName).someMethod("resultA");");
By using this technique, it becomes possible to dynamically generate callback method calls based on the variable name.
The above is the detailed content of How Can I Get a JavaScript Variable's Name as a String?. For more information, please follow other related articles on the PHP Chinese website!