我希望将一些函数嵌套在类属性中,如下所示。
不幸的是,它们无法访问类的主要范围。
我可以解决这个问题,而不需要为每个嵌套的函数传递一个对
不幸的是,它们无法访问类的主要范围。
我可以解决这个问题,而不需要为每个嵌套的函数传递一个对
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"
constructor: -> @errors = [] @functions: doStuff -> ...
吗? - Industrialfunctions
数组中的每个项目上使用javascript自己的bind
函数:https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Function/bind - biziclop