2011-09-26 73 views
0

我有一個CoffeeScript,我無法調用函數。但是,如果我聲明它的一個實例並將函數添加到它的實例中。我錯過了什麼?Coffeescript類丟失函數

功能不會被調用:

class testClass 
    username: 'Fred' 

    this.testFunction =()-> 
     alert 'test' 

    test = new testClass 

    test.testFunction() 

功能的工作原理:

class testClass 
    username: 'Fred' 

    test = new testClass 

    test.testFunction =()-> 
    alert 'test' 

    test.testFunction() 

回答

4

class本體內,this指向類本身,而不是它的原型。你想要的是

class testClass 
    username: 'Fred' 

    testFunction: -> 
    alert 'test' 

寫作this.testFunction =,在另一方面,創建testClass.testFunction

1

嘗試

class testClass 
    username: 'Fred' 
    testFunction:()-> 
     alert 'test' 

    test = new testClass 

    test.testFunction() 

CoffeeScript中具有類作爲第一層次的概念; this.testfunction =是錯誤的。您應該將其定義爲類型函數的字段。