O'Reilly logo

The Little Book on CoffeeScript by Alex MacCaw

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Chapter 2. CoffeeScript Classes

For some purists, classes in JavaScript seem to have the kind of effect that cloves of garlic have to Dracula; although, let’s be honest, if you’re that way inclined, you’re unlikely to be reading a book on CoffeeScript. However, it turns out that classes are just as useful in JavaScript as they are in other languages and CoffeeScript provides a great abstraction.

Behind the scenes, CoffeeScript is using JavaScript’s native prototype to create classes; adding a bit of syntactic sugar for static property inheritance and context persistence. As a developer, all that’s exposed to you is the class keyword:

class Animal

In the example above, Animal is the name of the class, and also the name of the resultant variable that you can use to create instances. Behind the scenes, CoffeeScript is using constructor functions, which means you can instantiate classes using the new operator:

animal = new Animal

Defining constructors (functions that get invoked upon instantiation) is simple—just use a function named constructor. This is akin to using Ruby’s initialize or Python’s __init__:

class Animal
  constructor: (name) ->
    @name = name

In fact, CoffeeScript provides a shorthand for the common pattern of setting instance properties. By prefixing arguments with @, CoffeeScript will automatically set the arguments as instance properties in the constructor. Indeed, this shorthand will also work for normal functions outside classes. The example below is equivalent to the last ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required