我想在類屬性中嵌套一些函數,如下所示。
不幸的是,他們無法訪問課程的主要範圍。coffeescript類中的範圍
我可以解決這個問題,而不通過每個嵌套函數參考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"
在構造函數中將它們綁定到這個/ @? – biziclop
你的意思是'構造函數: - > @errors = [] @functions:doStuff - > ...''? – Industrial
也許使用胖箭頭=> http://coffeescript.org/#fat_arrow我不是一個咖啡的主人,對不起:) – biziclop