我想在一个类属性中嵌套一些函数,如下所示。
不幸的是,他们无法访问课程的主要范围。
我可以在不向每个嵌套函数传递引用的情况下解决这个问题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"