1
 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从方法中设置的方法访问,而胖箭头什么也不做!有谁知道在这里做什么?

4

2 回答 2

3
 class SocialStudies
      constructor : (@val1,@val2) ->
          console.log 'constructed '+@val1+' | '+@val2
          @doAlerts =
            firstAlert : =>
                alert @val1
            secondAlert : =>
                alert @val2
于 2012-05-23T04:41:07.337 回答
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()
于 2012-05-24T12:13:56.557 回答