在CoffeeScript中未定义静态属性的问题

时间:2013-02-20 20:12:16

标签: javascript coffeescript

所以我正在为一个项目编写一些coffeescript,我正在尝试在类中创建一些静态属性。我一直在跟踪代码库中另一个成功完成同样事情的文件,但是我的工作没有用。

我的代码

class Messages
    @toggleUnreadConversations:()->
        # This is the line in question, Messages is defined with all the 
        # functions but the property ViewOnlyUnread is undefined

        Messages.ViewOnlyUnread = !Messages.ViewOnlyUnread

    @init:->
        @ViewOnlyUnread = false

代码库中成功使用静态属性的其他代码

class Map
   @CacheRealtor: (realtor) ->
        realtor.realtor_id = parseInt(realtor.realtor_id)

        # Here the static property IdToRealtorMap is defined 
        Map.IdToRealtorMap[parseInt(realtor.realtor_id)] = new Realtor()
   @Init: ->
       @IdToListingMap = []
       @IdToRealtorMap  = []

据我所知,当调用页面加载init时,这些init函数的调用方式相同。这两个类都是静态类,永远不会创建其中任何一个的实例。有没有人知道可能是什么问题?

1 个答案:

答案 0 :(得分:4)

init函数正在设置实例变量,但您的toggleUnreadConversations函数正在尝试引用它,就像它是您类的属性一样。

您应该使用@来引用init设置的实例变量:

class Messages
  @toggleUnreadConversations: ->

    # reference the instance variable
    @ViewOnlyUnread = !@ViewOnlyUnread

  @init: ->
    @ViewOnlyUnread = false