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

后端 未结 3 1447
臣服心动
臣服心动 2021-02-14 01:44

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

相关标签:
3条回答
  • 2021-02-14 01:54

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

    0 讨论(0)
  • 2021-02-14 02:11
    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.

    0 讨论(0)
  • 2021-02-14 02:14

    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.

    0 讨论(0)
提交回复
热议问题