从 CoffeeScript 文件导出类
如果我在一个单独的文件中定义了一个 CoffeeScript 类,并且从主脚本中调用该类,那么我可以使文件中的函数全局可见,但不能使该类全局可见。
包含的文件是:
root = exports ? this
root.add = (a, b) ->
return a + b
class root.userModel
username: 'Aaaa'
name: 'Bbbb'
我可以从我的主代码访问该函数。我怎样才能创建班级?
If I have a CoffeeScript class defined in a separate file, which I'm calling from my main script, I can make the functions within the file globally visible, but not the class.
The included file is:
root = exports ? this
root.add = (a, b) ->
return a + b
class root.userModel
username: 'Aaaa'
name: 'Bbbb'
I can access the function from my main code. How can I create the class?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您的代码确实会使
userModel
成为全局变量,假设exports
未定义且this
是window
。如果您遇到问题,请检查这些条件。Your code will indeed make
userModel
a global, assuming thatexports
is undefined andthis
iswindow
. If you're having problems, check those conditions.class ...
形式是一个返回值的表达式。因此,您需要将该class
表达式的结果分配给导出对象上的属性。像这样:更新:
哎呀,不是真的,应该可以作为
class root.userModel
或root.userModel = class userModel
正常工作。The
class ...
form is an expression that returns a value. So, you'll want to assign the result of thatclass
expression to a property on your export object. Like so:Update:
Oops, not true, should work fine either as
class root.userModel
or asroot.userModel = class userModel
.只需在类名称前添加“@”即可定义您的类:
Just define your class with a '@' before its name: