简体   繁体   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

Hopefully you get the idea. 希望你明白了。 I would like to access @val1 from a method set inside a method, and fat arrow does nothing! 我想从方法中的方法集中访问@val1 ,而胖箭头什么都不做! Does anyone know what to do here? 有谁知道该怎么办?

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

You can, of course, do it also like this: 当然,你也可以这样做:

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

This it otherwise equivalent to Keith Nicholas' answer, but allows using the super keyword in the methods in inherited classes, so you could do, say, like this: 这等同于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