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'.
Use the JavaScript function JSON.parse() to convert text into a JavaScript object: const obj = JSON.parse('{"name":"John", "age":30, "city":"New York"}');
There are two ways to create a String object: By string literal : Java String literal is created by using double quotes. For Example: String s=“Welcome”; By new keyword : Java String is created by using a keyword “new”.
Creating a JavaScript Object There are different ways to create new objects: Create a single object, using an object literal. Create a single object, with the keyword new . Define an object constructor, and then create objects of the constructed type.
function getTool(name){
return ( typeof window[name] === 'function' ) ?
new window[name]() : {/*some default*/};
}
Assumes PointerTool
constructor is defined in the global window
namespace. Replace that with whatever namespace you're using.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With