Variable name as a string in Javascript

2018-12-31 22:44发布

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?

标签: javascript
12条回答
十年一品温如言
2楼-- · 2018-12-31 22:49

Like Seth's answer, but uses Object.keys() instead:

const varToString = varObj => Object.keys(varObj)[0]

const someVar = 42
const displayName = varToString({someVar})
查看更多
不流泪的眼
3楼-- · 2018-12-31 22:50
var x = 2;
for(o in window){ 
   if(window[o] === x){
      alert(o);
   }
}

However, I think you should do like "karim79"

查看更多
萌妹纸的霸气范
4楼-- · 2018-12-31 22:58

In ES6, you could write something like:

let myVar = 'something';
let nameObject = {myVar};
let getVarNameFromObject = (nameObject) => {
  for(let varName in nameObject) {
    return varName;
  }
}
let varName = getVarNameFromObject(nameObject);

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/

查看更多
弹指情弦暗扣
5楼-- · 2018-12-31 23:01

No, there is not.
Besides, if you can write variablesName(myFirstName), you already know the variable name ("myFirstName").

查看更多
情到深处是孤独
6楼-- · 2018-12-31 23:02

This works for basic expressions

const nameof = exp => exp.toString().match(/[.](\w+)/)[1];

Example

nameof(() => options.displaySize);

Snippet:

var nameof = function (exp) { return exp.toString().match(/[.](\w+)/)[1]; };
var myFirstName = 'Chuck';
var varname = nameof(function () { return window.myFirstName; });
console.log(varname);

查看更多
看淡一切
7楼-- · 2018-12-31 23:06

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.

查看更多
登录 后发表回答