开发者

Export a class from a CoffeeScript file

开发者 https://www.devze.com 2023-04-07 06:56 出处:网络
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.

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 a开发者_JAVA百科ccess the function from my main code. How can I create the class?


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.


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.


Just define your class with a '@' before its name:

class @ClassName
  blablabla: -> blablalblablabla
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号