Skip to content

Instantly share code, notes, and snippets.

@franciscoj
Created August 5, 2011 18:17
Show Gist options
  • Save franciscoj/1128154 to your computer and use it in GitHub Desktop.
Save franciscoj/1128154 to your computer and use it in GitHub Desktop.
How to avoid using eval
var property = "property_name";
var object = new Object()
alert(object[property]) //will alert object.property_name
alert(object["property_name"]); //will alert object.property_name
alert(window["object"]["property_name"]) //will alert object.property_name
//assign a property to an object when
//you have its name calculated in a variable
var property_name = "a_great_property"
var object = new Object();
object[property_name] = "Hello world!";
alert(object.property_name); //will alert Hello world!
//call a function when you’ve it’s name
//calculated in a variable
var function_name = "whatever_function";
var object = {
whatever_function: function(){
alert("Hello world!");
}
}
object[function_name_](); // will alert Hello world!
//create an object from a class when
//you've it's name calculated in a variable
var klass_name = "Object";
var object = new window[klass_name];
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment