簡體   English   中英

Coffeescript類命名空間方法

[英]Coffeescript class namespaced methods

 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 ,而胖箭頭什么都不做! 有誰知道該怎么辦?

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

當然,你也可以這樣做:

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()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM