Skip to content

Instantly share code, notes, and snippets.

@jineeshjohn
Created March 6, 2013 10:32
Show Gist options
  • Save jineeshjohn/5098412 to your computer and use it in GitHub Desktop.
Save jineeshjohn/5098412 to your computer and use it in GitHub Desktop.
String into a javascript function call. Better way to create instance for dynamic class names
var Y = (function(){
return {
Car:function(model){
this.model = model;
this.applyBreak = function(){
alert("done break!!");
}
}
}
})();
var json = {
className:"Car"
}
//Solution 1 with eval - bad
var str = "new "+json['className']+"(2007)";
var cc = eval(str);
//Solution 2 subscript notation -- better
function createInstance(name,param){
return new Y[name](param);
}
var cc = createInstance(json['className'],2007);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment