I would like to nest a number of functions inside a class property as shown below.
Unfortunately, they won't get access to the main scope of the class.
Can I solve this without passing each nested function a reference to 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
Non-working alternative using suggested fat arrow:
class myClass
constructor: ->
@errors = []
@functions:
doStuff: =>
@errors.push "I wont work either" # TypeError: Cannot call method 'toString' of undefined
Optional alternative, which doesn't write to the global this.errors property:
class myClass
constructor: ->
@functions =
errors: []
doStuff: ->
@errors.push "I will write to functions.errors only"
constructor: -> @errors = [] @functions: doStuff -> ...?