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

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

提交回复
热议问题