Is there a way to refer to a Javascript variable with a string that contains its name?
example:
var myText = 'hello world!';
var someString = 'myText';
//how to output myText value using someString?
If that variable is on the global scope, you can use the bracket notation on the global object:
var myText = 'hello world!';
var someString = 'myText';
alert(window[someString]);
In JavaScript, there is no standard for creating a 'Master Object', or any built-in method to access variables on the initial scope with a string reference that I am aware of.
However, if you are using JavaScript for web development on a browser, the window Object will give you complete access to your current scope. For example:
myVar = "This is my var";
if(myVar == window.myVar){
/*
This statement would return true
Because both variables reference
the same string;
*/
}
This method will allow you to reference any scope-variable WITHOUT making it a string, but you can also use a string as needed with the bracket ([]) Selectors.
window['myVar']
It is worth mentioning that keeping data as a variable directly on the current scope leaves it open to be re-defined by other scripts running. Your variable can be overwritten by function argument names, for loop variables, and simply by assigning a new value to that variable.
To overcome this, I suggest using an Object to store all relevant data to your application (Static And/Or OOP). Like this:
$myApp = {
var1 : 'This is Var1',
apply : function(){
alert('Started!');
}
}
//Referencing relative variables
alert($myApp.var1);