coffeescript - 从字符串中的类名实例化 CoffeeScript 类

标签 coffeescript

当字符串中只有类的名称时,如何在 CoffeeScript 中实例化类?

class Dog
  bark:->
    "Woof"

className = "Dog"
dog = new className  # <--- I would like to create an instance here using the string

最佳答案

稍有远见,您就可以轻松做到这一点,并保护自己免受使用 eval .在要按名称实例化的类的某处保留一个列表:

class Dog
  bark:->
    "Woof"

# Or window.named_classes if you need to access
# `named_classes` globally (or just in another
# CoffeeScript file).
named_classes = { Dog: Dog }

然后使用您的查找表而不是 eval :
name = 'Dog'
dog  = new named_classes[name]

当你说 class Dog ,你最终得到一个名为 Dog 的局部变量:
var Dog;
Dog = (function() { /* ... */ })();

并且无法获取本地 JavaScript 变量,除非您将其存储在可以通过名称访问的地方。另请注意 eval如果您定义 Dog 将不起作用在一个 CoffeeScript 文件中,并希望访问另一个文件,CoffeeScript wraps each file in self-executing anonymous function to limit variable scope :

all CoffeeScript output is wrapped in an anonymous function: (function(){ ... })(); This safety wrapper, combined with the automatic generation of the var keyword, make it exceedingly difficult to pollute the global namespace by accident.

If you'd like to create top-level variables for other scripts to use, attach them as properties on window, or on the exports object in CommonJS.

关于coffeescript - 从字符串中的类名实例化 CoffeeScript 类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8912308/

相关文章:

coffeescript - 粗箭头 'this' 范围

javascript - 没有 CoffeeScript 的 TowerJS?

javascript - Accordion 面板不应在 if 条件下打开 - coffeescript

javascript - 全局命名空间和 CoffeeScript 循环中的 this

javascript - AngularJS无法将ngresource响应分配给范围

node.js - Nodejs Coffescript 无需翻译和咖啡命令即可执行

javascript - 使用 js2coffee 将整个项目转换为 CoffeeScript

javascript - 调度程序未在 Jest 单元测试中注册回调

ruby-on-rails - 我可以在 render.js 上执行的 View 中使用 CoffeeScript 吗?

javascript - 网络音频 API : Clicks on volume change with slider