Home > Web Front-end > JS Tutorial > How Can I Get a JavaScript Variable's Name as a String?

How Can I Get a JavaScript Variable's Name as a String?

Susan Sarandon
Release: 2024-12-08 10:34:14
Original
872 people have browsed it

How Can I Get a JavaScript Variable's Name as a String?

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]
Copy after login

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();

...
Copy after login

From the other program:

evaluateJavascriptInBrowser("(instanceName).someMethod("resultA");");
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template