2013-05-08 58 views
3

我從咖啡開始。 (與英語一樣,所以我對任何語法錯誤抱歉。)看看這個類:Coffeescript未定義的類?

class Stuff 
    handleStuff = (stuff) -> 
    alert('handling stuff'); 

它編譯成:

var Stuff; 
Stuff = (function() { 
    var handleStuff; 

    function Stuff() {} 

    handleStuff = function(stuff) { 
    return alert('handling stuff'); 
    }; 

    return Stuff; 

})(); 

的HTML我創造的東西的一個實例,但該死的東西說它沒有方法handleStuff。 爲什麼?

回答

5

你想handleStuff要對原型,所以改成這樣:

class Stuff 
    handleStuff: (stuff) -> 
    alert('handling stuff'); 

的區別是一個冒號與等號。

哪個編譯爲:

var Stuff; 

Stuff = (function() { 
    function Stuff() {} 

    Stuff.prototype.handleStuff = function(stuff) { 
    return alert('handling stuff'); 
    }; 

    return Stuff; 

})(); 

你可以看到它在這裏工作:對在documentation類和類成員

<script src="http://github.com/jashkenas/coffee-script/raw/master/extras/coffee-script.js"></script> 
 
<script type="text/coffeescript"> 
 
class Stuff 
 
    handleStuff: (stuff) -> 
 
    alert('handling stuff'); 
 
    
 
stuffInstance = new Stuff() 
 
stuffInstance.handleStuff() 
 
</script>

和更多信息。

+0

非常感謝。我永遠不會明白。 – Adinan 2013-05-08 12:34:10