2015-03-13 100 views
0

在其他OOP語言,下面是一個抽象的CoffeeScript的繼承:靜態變量/方法

class AbstractClass 
    myVar: null 

    @doSomething: -> 
    console.log myVar 

class Child extends AbstractClass 
    myVar: 'I am a child' 

調用Child.doSomething()應打印「我是孩子」一個常見的形式。 我也應該能夠傳遞Child.doSomething作爲回調,並讓它打印相同。我嘗試過使用分號或w/o @的所有組合,使用分號並等於定義myVar,我無法弄清楚。在CoffeeScript中做到這一點的正確方法是什麼?

編輯

我覺得我過於簡化我的例子,因爲我無法得到它的工作(進行編輯:現在有了這個解決方案的工作)。這裏是真正的代碼(在地方建議的解決方案):

class AbstractController 
    @Model: null 

    @index: (req, res) -> 
    console.log @ 
    console.log @Model 
    @Model.all?(req.params) 

class OrganizationController extends AbstractController 
    @Model: require "../../classes/community/Organization" 

在我的路由文件

(express, controller) -> 
    router = express.Router({mergeParams: true}) 
    throw new Error("Model not defined") unless controller.Model? 
    console.log controller 
    router 
    .get "/:#{single}", _.bind(controller.show, controller) 
    .get "/", _.bind(controller.index, controller) 
    .post "/", _.bind(controller.post, controller) 

傳遞OrganizationController該功能正常記錄的OrganizationController對象,所以我知道它越來越有:

{ [Function: OrganizationController] 
    Model: { [Function: Organization] ...}, 
    index: [Function], 
    __super__: {} } 

但是,當我打的路線,兩人的console.log調用打印出

{ [Function: AbstractController] 
    Model: null, 
    index: [Function] } 
null 

我得到一個錯誤:「不能讀取屬性的空‘所有’」

回答

3

你失蹤了幾個@秒。下面的打印I am a child

class AbstractClass 
    @myVar: null 

    @doSomething: -> 
    console.log @myVar 

class Child extends AbstractClass 
    @myVar: 'I am a child' 

Child.doSomething() 

但是,如果你想要把它作爲一個回調函數,你需要將其綁定到Child

callf = (f) -> 
    f() 

callf Child.doSomething    # prints undefined 
callf Child.doSomething.bind(Child) # prints I am a child