当我只在字符串中有类的名称时,如何在CoffeeScript中实例化一个类?
class Dog
bark:->
"Woof"
className = "Dog"
dog = new className # <--- I would like to create an instance here using the string
Run Code Online (Sandbox Code Playgroud)
mu *_*ort 11
有一点远见,你可以很容易地做到这一点,并保护自己免受使用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 }
Run Code Online (Sandbox Code Playgroud)
然后使用您的查找表而不是eval:
name = 'Dog'
dog = new named_classes[name]
Run Code Online (Sandbox Code Playgroud)
当你说class Dog,你最终得到一个名为的局部变量Dog:
var Dog;
Dog = (function() { /* ... */ })();
Run Code Online (Sandbox Code Playgroud)
并且无法获取本地JavaScript变量,除非您将其存储在可以按名称访问的位置.另请注意,eval如果您Dog在一个CoffeeScript文件中定义并想要另一个文件,则CoffeeScript将无法使用,CoffeeScript将自动执行的匿名函数中的每个文件包装起来以限制变量范围:
所有的CoffeeScript输出被包裹在一个匿名函数:
(function(){ ... })(); 这个安全包装器与var关键字的自动生成相结合,使得非常难以意外地污染全局命名空间.如果要为其他要使用的脚本创建顶级变量,请将它们作为属性附加到窗口或CommonJS中的exports对象上.
| 归档时间: |
|
| 查看次数: |
5036 次 |
| 最近记录: |