Coffeescript类命名空间方法

时间:2012-05-23 04:34:39

标签: javascript oop coffeescript

 class SocialStudies
      constructor : (@val1,@val2) ->
          console.log 'constructed '+@val1+' | '+@val2
      doAlerts :
          firstAlert : =>
               alert @val1
          secondAlert : =>
               alert @val2

 secondPeriod = new SocialStudies 'git to class!', 'no recess for you!'

 secondPeriod.doAlerts.firstAlert() // error this.val1 is not defined

希望你明白了。我想从方法中的方法集中访问@val1,而胖箭头什么都不做!有谁知道该怎么办?

2 个答案:

答案 0 :(得分:3)

 class SocialStudies
      constructor : (@val1,@val2) ->
          console.log 'constructed '+@val1+' | '+@val2
          @doAlerts =
            firstAlert : =>
                alert @val1
            secondAlert : =>
                alert @val2

答案 1 :(得分:0)

当然,您也可以这样做:

class SocialStudies
  constructor: (@val1, @val2) ->
    @doAlerts = firstAlert: @firstAlert, secondAlert: @secondAlert
  firstAlert: =>
    alert @val1
  secondAlert: =>
    alert @val2

这等同于Keith Nicholas的答案,但允许在继承类的方法中使用 super 关键字,所以你可以这样做:

class AntiSocialStudies extends SocialStudies
  secondAlert: =>
    @val2 += ' no solitary drinking until 3PM.'
    super

secondPeriod = new AntiSocialStudies 'git to class!', 'no recess for you!'
secondPeriod.doAlerts.secondAlert()