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

后端 未结 3 1444
臣服心动
臣服心动 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 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.

提交回复
热议问题