How do I create a new object in javascript based on a type-string?

怎甘沉沦 提交于 2019-12-09 09:27:33

问题


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


回答1:


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.




回答2:


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




回答3:


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.



来源:https://stackoverflow.com/questions/4360680/how-do-i-create-a-new-object-in-javascript-based-on-a-type-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!