Export a class from a Coffeescript file

2020-03-10 06:18发布

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?

3条回答
我命由我不由天
2楼-- · 2020-03-10 07:00

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

class @ClassName
  blablabla: -> blablalblablabla
查看更多
SAY GOODBYE
3楼-- · 2020-03-10 07:02

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.

查看更多
我想做一个坏孩纸
4楼-- · 2020-03-10 07:09

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.

查看更多
登录 后发表回答