Skip to content Skip to sidebar Skip to footer

Javascript Get Variable In Current Scope By Name

So I have a variable and a string of that variable name function Factory(string) { var foo = 'bar' console.log('foo is equal to ' + this[string]) } how can I get the variable

Solution 1:

this[string] assumes that you have a variable this.foo which you don't.


You can do some eval manipulation if you want, which will work in your case:

functionFactory(string) {
  var foo = 'bar'
  console.log("foo is equal to " + eval('(function(){return ' + string + '})()'))
}

Solution 2:

while you can use eval, i believe the proper approach is to use an object:

functionFactory(string) {
  var variables = {foo: 'bar'};
  console.log(string + " is equal to " + variables[string])
}

Post a Comment for "Javascript Get Variable In Current Scope By Name"