Defining a class in CoffeeScript
A class, in essence, is not much more than a name and a collection of properties that define its behavior. A class is defined once, but can be instantiated many times.
Here's the simplest class definition in CoffeeScript:
class Airplane
That's it! We now have an Airplane
class, and we can create instances of it.
plane = new Airplane() plane.color = "white"
The new
keyword instantiates the object just like in JavaScript. The parentheses are optional, but I prefer to leave them in, to keep it consistent with other function invocations with no arguments. We can set arbitrary properties on our plane, just as we can do with any object in JavaScript.
Attaching methods to a class
So far we haven't done much we couldn't accomplish just as well with a generic object. Let's attach a method to our class' prototype.
Note
A method is just a function that's attached to an object.
class Airplane takeOff: -> console.log "Vrrrroooom!"
Now we're making progress! CoffeeScript...