Javascript CoffeeScript类PrivateMethod使用实例属性问题
我目前正在编写CoffeeScript,遇到了一个恼人的问题。 当我将类privateMethod编写为Javascript CoffeeScript类PrivateMethod使用实例属性问题,javascript,coffeescript,Javascript,Coffeescript,我目前正在编写CoffeeScript,遇到了一个恼人的问题。 当我将类privateMethod编写为privateMethod=->时,如果我想在方法内部使用@a.k.a这个属性,由于范围问题,我会得到语法错误。 请参见下面的示例代码 class TestClass constructor : (@name = "NoName") -> privateFunc = -> console.log @name callPrivateFunc : ->
privateMethod=->
时,如果我想在方法内部使用@
a.k.a这个
属性,由于范围问题,我会得到语法错误。
请参见下面的示例代码
class TestClass
constructor : (@name = "NoName") ->
privateFunc = ->
console.log @name
callPrivateFunc : ->
privateFunc()
testClass = new TestClass("John")
testClass.callPrivateFunc() # @name is undefined
到目前为止,我找到了两种方法来避免这个问题
案例1:使用。呼叫
class TestClass
constructor : (@name = "NoName") ->
privateFunc = ->
console.log @name
callPrivateFunc : ->
privateFunc.call(this)
testClass = new TestClass("John")
testClass.callPrivateFunc() # "John"
案例2:将此参数作为函数参数传递
class TestClass
constructor : (@name = "NoName") ->
privateFunc = (that)->
console.log that.name
callPrivateFunc : ->
privateFunc(@)
testClass = new TestClass("John")
testClass.callPrivateFunc() # "John"
我的问题是,这些方法是否适合使用使用this
的私有方法?
或者是否有合适的方式/事实标准
谢谢你的回答至于“适当”的方式,我认为没有。使用.call对我来说更合适。这就是电话存在的部分原因。我还要看看Function.prototype.bind。它用于将thisArg绑定到函数。请看这里: .绑定示例:
class TestClass
constructor : (@name = "NoName") -> privateFunc.bind(this)();
privateFunc = ->
alert @name
testClass = new TestClass("John") # alerts "John"
e;这也值得一读: