Coffeescript Undefined类?

Adi*_*nan 3 methods visibility class coffeescript

我从coffeescript开始.(还有英语,所以我对任何语法错误感到抱歉.)看看这堂课:

class Stuff
  handleStuff = (stuff) ->
    alert('handling stuff');
Run Code Online (Sandbox Code Playgroud)

它编译为:

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

  function Stuff() {}

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

  return Stuff;

})();
Run Code Online (Sandbox Code Playgroud)

在Html上我创建了一个Stuff实例,但该死的东西说它没有方法handleStuff.为什么?

vcs*_*nes 5

你想handleStuff成为原型,所以改成它:

class Stuff
  handleStuff: (stuff) ->
    alert('handling stuff');
Run Code Online (Sandbox Code Playgroud)

区别在于冒号与等于.

编译为:

var Stuff;

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

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

  return Stuff;

})();
Run Code Online (Sandbox Code Playgroud)

你可以看到它在这里工作:

<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>
Run Code Online (Sandbox Code Playgroud)

有关文档中的类和类成员的更多信息.