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 lon
You should consider rethinking your approach. It would be better to have something like a Tools
object, which would have the tools as properties, like
Tools = {"SelectTool": SelectTool /* etc */}`.
This way, you could access the tools both as new Tools.SelectTool
and new Tools[var_with_tool_name]
.
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.
In your example, you're declaring PointerTool
as a function in the global scope. Assuming your javascript is running the browser, the "global scope" is actually the same as the window
object. That means that if you have a constructor:
function PointerTool() {
...
}
that's the same as this:
window.PointerTool = function() {
...
}
So now, in your getTool function, you can access your constructor functions like this:
function getTool(name){
return new window[name]();
}
A more "future proof" way to do this would be to do define your own namespace object, in which you'll place all your various tool constructors. Something like this ("myproject" would be the short name of your project or system):
var myproject = { tools: {} };
// Pointer Tool Constructor
myproject.tools.PointerTool = function() {
...
}
// Line Tool Constructor
myproject.tools.LineTool = function() {
...
}
// and so on
Then your getTool function would look like this:
function getTool(name){
return new myproject.tools[name]();
}
This approach keeps your stuff isolated from whatever other stuff happens to be defined in the global/window scope.