How do I create a new object in javascript based on a variable type-string (containing the name of the object)?
Now I have: (with more tools coming the list will get longer...)
function getTool(name){
switch(name){
case "SelectTool":
return new SelectTool();
break;
case "LineTool":
return new LineTool();
break;
case "BlurTool":
return new BlurTool();
break;
case "PointerTool":
default:
return new PointerTool();
break;
}
}
And defined my tools like:
PointerTool.prototype = new Tool;
PointerTool.prototype.constructor = PointerTool;
function PointerTool(){
this.name = "PointerTool";
}
PointerTool.prototype.click = function(x, y){
info("You clicked at: "+x+", "+y);
}
I would like to get ride of the (growing) switch statement, it seems 'wrong'.
eval()is not the correct solution here, but I'm curious why you assert that "eval should be avoided at all costs". It is a non-deprecated feature of the language, with appropriate (and inappropriate) uses -- just like every other feature.evalis the only answer, and that is when it should be used. If these objects were defined within an anonymous self executing function, they could not be referenced usingwindow[constructor].