以下に示すように、クラス プロパティ内に多数の関数をネストしたいと考えています。
残念ながら、クラスのメイン スコープにはアクセスできません。
ネストされた各関数への参照を渡さずにこれを解決できますthis
か?
class myClass
constructor: -> @errors = []
doSomething: -> @errors.push "I work as expected"
functions:
doStuff: ->
@errors.push "I cant access @errors" # => TypeError: Cannot call method 'push' of undefined
ugly: (context) ->
context.errors.push "It works, but I am ugly" # Works fine but requires scope injection
提案された太い矢印を使用した機能しない代替手段:
class myClass
constructor: ->
@errors = []
@functions:
doStuff: =>
@errors.push "I wont work either" # TypeError: Cannot call method 'toString' of undefined
this.errors
グローバルプロパティに書き込まないオプションの代替手段:
class myClass
constructor: ->
@functions =
errors: []
doStuff: ->
@errors.push "I will write to functions.errors only"