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’.
Assumes
PointerToolconstructor is defined in the globalwindownamespace. Replace that with whatever namespace you’re using.