Question

Working example with global var:

var example_var = 'global var example';

var x = function(){
    var var_name = 'example_var';
    alert('Global var value is: ' + window[var_name]);
}

How can I do same thing with a local variable? Like this (not working example):

var x = function(){
    var example_var = 'Local var example';
    var var_name = 'example_var';
    alert('Local var value is: ' + window[var_name]);
}
Was it helpful?

Solution

You don't want to use eval; a locally scoped object might be your best option:

var x = function(){
    var self = {};
    self.example_var = 'Local var example';

    var var_name = 'example_var';

    alert('Local var value is: ' + self[var_name]);
}

OTHER TIPS

If you have no other way, you can try eval it

var x = function(){
    var example_var = 'Local var example';
    var var_name = 'example_var';
    alert('Local var value is: ' + eval(var_name));
}

possibly:

var x = function(){
    var example_var = 'Local var example';
    var var_name = example_var;
    alert('Local var value is: ' + var_name);
}

or:

  var x = function(){
        var example_var = 'Local var example';
       window.var_name = example_var;
        alert('Local var value is: ' + window[var_name]);
    }

or

  var x = function(){
            var var_name = 'Local var example';    
            alert('Local var value is: ' + var_name);
        }

At the moment there are two solutions to this problem.
1. eval(), but i really don't like to use evil()
2. we can change variable declaration from var to this:

var x = function(){
    this.example_var = 'this.var example';
    this.var_name = 'example_var';
    alert('Local variable value is: ' + this[var_name]);
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow