Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Coffeescript Undefined class?

I am starting with coffeescript. (And english as well, so I'm sorry about any grammatical error.) Look at this class:

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

It compiles to :

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

  function Stuff() {}

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

  return Stuff;

})();

on Html I created an instance of Stuff, but the damn thing say it has no method handleStuff. Why?

like image 642
Adinan Avatar asked Dec 04 '25 18:12

Adinan


1 Answers

You want handleStuff to be on the prototype, so change it to this:

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

The difference is a colon vs. an equals.

Which compiles to:

var Stuff;

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

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

  return Stuff;

})();

You can see it working here:

<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>

And more information on classes and class members in the documentation.

like image 114
vcsjones Avatar answered Dec 06 '25 13:12

vcsjones



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!