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