2014-08-28 25 views
0

我目前正在使用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一個私有方法有道? 或有任何適當的方式/事實標準?

謝謝您的回答

回答

0

至於一個「正確」的方式,我不認爲有一個。使用.call感覺對我更爲正確。這就是爲什麼.call存在的部分原因。我也會看看Function.prototype.bind。它用於將thisArg綁定到函數。看看這裏:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind

.bind例如:

class TestClass 
    constructor : (@name = "NoName") -> privateFunc.bind(this)(); 
    privateFunc = -> 
    alert @name 

testClass = new TestClass("John") # alerts "John" 

ë;這也值得一讀:http://jsforallof.us/2014/07/08/var-that-this/