如何基于类型字符串在javascript中创建新对象? [英] How do I create a new object in javascript based on a type-string?

查看:80
本文介绍了如何基于类型字符串在javascript中创建新对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何基于可变类型字符串(包含对象名称)在javascript中创建新对象?

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);
}

我想了解(不断增长的)switch语句,

I would like to get ride of the (growing) switch statement, it seems 'wrong'.

推荐答案

function getTool(name){
  return ( typeof window[name] === 'function' ) ? 
                                    new window[name]() : {/*some default*/};
}

假设 PointerTool 构造函数在全局窗口命名空间中定义。将其替换为您使用的任何名称空间。

Assumes PointerTool constructor is defined in the global window namespace. Replace that with whatever namespace you're using.

这篇关于如何基于类型字符串在javascript中创建新对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆