Export a class from a Coffeescript file

戏子无情 提交于 2019-12-19 05:18:58

问题


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.

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?


回答1:


Your code will indeed make userModel a global, assuming that exports is undefined and this is window. If you're having problems, check those conditions.




回答2:


The class ... form is an expression that returns a value. So, you'll want to assign the result of that class expression to a property on your export object. Like so:

root.userModel = class userModel
  username: 'Aaaa'
  name: 'Bbbb'

Update:

Oops, not true, should work fine either as class root.userModel or as root.userModel = class userModel.




回答3:


just define your class with a '@' before its name

class @ClassName
  blablabla: -> blablalblablabla


来源:https://stackoverflow.com/questions/7533191/export-a-class-from-a-coffeescript-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!