因此,我正在为一个项目编写一些 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 函数的调用方式相同。这两个类都是静态类,永远不会创建它们中的任何一个的实例。有谁知道可能是什么问题?
最佳答案
init
函数正在设置一个实例变量,但您的 toggleUnreadConversations
函数试图引用它,就好像它是您的类的属性一样.
您应该使用@
来引用init
设置的实例变量:
class Messages
@toggleUnreadConversations: ->
# reference the instance variable
@ViewOnlyUnread = !@ViewOnlyUnread
@init: ->
@ViewOnlyUnread = false
关于javascript - CoffeeScript 中未定义静态属性的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14989023/