当字符串中只有类的名称时,如何在 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 thevar
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/