我目前正在使用CoffeeScript並遇到惱人的問題。 當我做類privateMethod寫作privateMethod = ->
和如果我想要使用@
a.k.a this
屬性內部的方法,由於範圍問題,我得到語法錯誤。 見下文使用實例屬性的CoffeeScript類PrivateMethod問題
class TestClass
constructor : (@name = "NoName") ->
privateFunc = ->
console.log @name
callPrivateFunc : ->
privateFunc()
testClass = new TestClass("John")
testClass.callPrivateFunc() # @name is undefined
示例代碼,我發現2的方式來回避問題爲止。
殼體1:使用.CALL
class TestClass
constructor : (@name = "NoName") ->
privateFunc = ->
console.log @name
callPrivateFunc : ->
privateFunc.call(this)
testClass = new TestClass("John")
testClass.callPrivateFunc() # "John"
情況2:通過這ARG作爲功能PARAM
class TestClass
constructor : (@name = "NoName") ->
privateFunc = (that)->
console.log that.name
callPrivateFunc : ->
privateFunc(@)
testClass = new TestClass("John")
testClass.callPrivateFunc() # "John"
我的問題是,這些方法中使用它使用this
一個私有方法有道? 或有任何適當的方式/事實標準?
謝謝您的回答