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
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.