CoffeeScript: The five minute guide to Classes

Post to Twitter

CoffeeScript is a language that compiles into JavaScript. Once you try CoffeeScript it is very hard to resist not using it for any kind of JavaScript project especially those that use Node.js. Today I’m going to quickly go over how easy CoffeeScript makes working with classes.


[ad name=”Google Adsense”]

Before you begin: Please be aware that although I’m talking about classes, JavaScript doesn’t actually support real classes in the sense like how classes work in C++, Java, Python, etc.

I’m going to use the NPM package coffee-script to do these demos. I’m on OS X so I installed Node.js and then from the Terminal I created a folder called TryCoffee. Inside of that folder I installed the CoffeeScript NPM package globally.

Warning: I’m using sudo here to avoid some permission issues on OS X. If your not comfortable using sudo that is reasonable given that your allowing something to have root access to your machine. There are other ways to install without using sudo – see the note below.

$ mkdir TryCoffee
$ cd TryCoffee
$ sudo npm install -g coffee-script

Note: If you don’t want to install CoffeeScript globally then do this instead:

$ npm install coffee-script

Create a new file in the folder and call it spaceship.coffee. Inside of that file we will create a very simple Spaceship class.

class Spaceship
		
spcshp = new Spaceship()

Although the class won’t do anything go ahead and run it regardless:

$ coffee spaceship.coffee

You won’t see any visual results but if everything is installed correctly then you shouldn’t see any errors. Let’s go ahead and expand on the class to do something.

class Spaceship

	move: (speed = 1) ->
		console.log "Spaceship speed: " + speed
		
spcshp = new Spaceship()
spcshp.move()

So I’ve added a function to the class called move that takes a parameter of speed which if I don’t set it then the default speed value of 1 will be used.

So let’s run it again with the new code.

$ coffee spaceship.coffee

Result:

Spaceship speed: 1

Ok, so maybe now your wondering this is pretty simple to create a class in CoffeeScript but what does the actual JavaScript look like. Well you can generate JavaScript from your CoffeeScript files easily by doing this:

$ coffee --output js/ --compile spaceship.coffee

Basically I’m telling Coffee to put the resulting JavaScript generated files into a folder called js.

The resulting generated JavaScript file looks like this:

// Generated by CoffeeScript 1.3.3
(function() {
  var Spaceship, spcshp;

  Spaceship = (function() {

    function Spaceship() {}

    Spaceship.prototype.move = function(speed) {
      if (speed == null) {
        speed = 1;
      }
      return console.log("Spaceship speed: " + speed);
    };

    return Spaceship;

  })();

  spcshp = new Spaceship();

  spcshp.move();

}).call(this);

You can also make the above command shorter by just typing this:

$ coffee -o js/ -c spaceship.coffee

Okay, so now we’ve decided we will just pass in the spaceship’s speed through a constructor. How do we use constructors in CoffeeScript? Very easily actually.

class Spaceship

	constructor: (@speed = 1) ->
		console.log "New spaceship created with a speed of #{@speed}"

	move: () ->
		console.log "The spaceship is moving now at a speed of #{@speed}"
		
spcshp = new Spaceship()
spcshp.move()

Using @speed in the above constructor we are doing the equalivent of this.speed in JavaScript.

Go ahead and run this modified class now.

$ coffee spaceship.coffee

Result:

New spaceship created with a speed of 1
The spaceship is moving now at a speed of 1

The JavaScript that is generated will look like this:

// Generated by CoffeeScript 1.3.3
(function() {
  var Spaceship, spcshp;

  Spaceship = (function() {

    function Spaceship(speed) {
      this.speed = speed != null ? speed : 1;
      console.log("New spaceship created with a speed of " + this.speed);
    }

    Spaceship.prototype.move = function() {
      return console.log("The spaceship is moving now at a speed of " + this.speed);
    };

    return Spaceship;

  })();

  spcshp = new Spaceship();

  spcshp.move();

}).call(this);

By now you can probably see how much typing CoffeeScript can save you and how much easier it is to read. Let’s expand on our class some more by using inheritance.

class Spaceship

	constructor: (@speed = 1, @spaceShipType = 'spaceship') ->
		console.log "New #{@spaceShipType} created with a speed of #{@speed}"

	move: () ->
		console.log "The #{@spaceShipType} is moving now at a speed of #{@speed}"


class FlyingSaucer extends Spaceship

	constructor: ->
		super 5, 'Flying Saucer'
		
	useDeathRay: ->
		console.log "The flying saucer is using a death ray!"

spcshp = new Spaceship()
spcshp.move()

flySaucr = new FlyingSaucer()
flySaucr.move()
flySaucr.useDeathRay()

So I’ve created a generic Spaceship class that takes two constructor parameters complete with default values if not specified. I then modified the console.out commands to use the passed in parameters to make the class more generic. Using extend I then inherited the Spaceship class to my new FlyingSaucer class which then overrides the default constructor values with the appropriate values for my new class.

Result:

New spaceship created with a speed of 1
The spaceship is moving now at a speed of 1
New Flying Saucer created with a speed of 5
The Flying Saucer is moving now at a speed of 5
The flying saucer is using a death ray!

Here is the generated JavaScript:

// Generated by CoffeeScript 1.3.3
(function() {
  var FlyingSaucer, Spaceship, flySaucr, spcshp,
    __hasProp = {}.hasOwnProperty,
    __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };

  Spaceship = (function() {

    function Spaceship(speed, spaceShipType) {
      this.speed = speed != null ? speed : 1;
      this.spaceShipType = spaceShipType != null ? spaceShipType : 'spaceship';
      console.log("New " + this.spaceShipType + " created with a speed of " + this.speed);
    }

    Spaceship.prototype.move = function() {
      return console.log("The " + this.spaceShipType + " is moving now at a speed of " + this.speed);
    };

    return Spaceship;

  })();

  FlyingSaucer = (function(_super) {

    __extends(FlyingSaucer, _super);

    function FlyingSaucer() {
      FlyingSaucer.__super__.constructor.call(this, 5, 'Flying Saucer');
    }

    FlyingSaucer.prototype.useDeathRay = function() {
      return console.log("The flying saucer is using a death ray!");
    };

    return FlyingSaucer;

  })(Spaceship);

  spcshp = new Spaceship();

  spcshp.move();

  flySaucr = new FlyingSaucer();

  flySaucr.move();

  flySaucr.useDeathRay();

}).call(this);

F.Y.I – I’m currently reading a very good CoffeeScript book which is available on Amazon:

Post to Twitter

This entry was posted in CoffeeScript, JavaScript. Bookmark the permalink.

One Response to CoffeeScript: The five minute guide to Classes

  1. Pingback: CoffeeScript: 10 tips with examples to increase your productivity | Giant Flying Saucer

Comments are closed.