Blog

  • Home /
  • Blog /
  • Exploring CoffeeScript Part 4 - Objects and Classes

Exploring CoffeeScript Part 4 - Objects and Classes

July 26, 2011

For this blog post, we’re going to continue our journey through the wonderful world of CoffeeScript, exploring objects and classes.

Also make sure to check out the previous installments:

Objects

Most of us have know how the object literal notation looks like using plain old JavaScript. Here’s a simple example:

Lets have a look at how define the exact same object using CoffeeScript.

As you can see, the CoffeeScript equivalent involves less overhead which naturally results in a more compact syntax. For object literals we don't have to provide curly braces and commas, taking full advantage of significant whitespace.

In this basic example, we directly assign values for the different properties which is not very common. Suppose that we want to create podcast objects by calling a factory method specifying the necessary parameter values:

Again, CoffeeScript can save us some typing here as we don’t need to provide both the property name and the corresponding variable name if they are both the same. In this case we can rely on conventions to create a new podcast object.

Note that we need to specify curly braces for both the resulting podcast object as for the nested details object because otherwise we’ll get some parser errors. Either way, CoffeeScript gets the most out of every keystroke :-).

Classes

JavaScript is not a ‘classical’ language but a prototypal object language. There are several JavaScript libraries out there that have made an attempt to bring some form of class like syntax into the language. It’s my personal belief that by fully embracing the prototypical nature of JavaScript that we can gain the true benefits of this great language. However I do recognize that a class like syntax can save us from the syntactical and mental burden that is often seen with prototypical inheritance in JavaScript. Again, CoffeeScript is here to save the day.

By providing a class-style syntax, CoffeeScript effectively provides us with a useful abstraction on top of JavaScript’s prototype capabilities, also applying all the well-known best practices in the process. This enables us to write code that is much more concise and therefore also more clear while still taking advantage of the benefits of the JavaScript object model.

Let’s talk code, shall we?

Here we have three classes. Both the Podcast and the Screencast class derive from the Medium class using the extends keyword. First have a look at the constructor functions. CoffeeScript lets us define dedicated functions that will be executed upon instantiation. Notice the shorthand syntax for property initialization. Instead of constructor: (name) –> @name = name we can simply use the equivalent constructor: (@name). This shorthand will also work for normal functions outside of classes. Remember, every keystroke counts! The constructor functions of the derived classes invoke the constructor of the base class by simply calling super, which translates into a call to an ancestor method of the same name.

Instance methods and properties can be defined exactly the same way as we saw earlier when we discussed objects. Obviously, these can only be used after we create an instance of a class.

But we can also have static methods and properties. These cannot be invoked on instances of a class but only directly on the class object itself.

We’ve already used the shorthand syntax here. We could also use the following notation for defining this static method:

Remember from the previous post that CoffeeScript uses the ‘@’ symbol to alias this. Every keystroke counts!

One of the key tenets of object-oriented programming using a classical language is polymorphism. Don’t worry, CoffeeScript got this covered as well.

Here we have a function that takes in a Medium object and simply invokes the playOn() function. The playOn() functions of the derived classes will be invoked and not the one defined in the base class. 

In the previous post we mentioned that we can reuse methods from other objects using the call()/apply() methods defined on the prototype of Function. This can also be done when we’re using classes in CoffeeScript.

We can use the hash rocket operator (or fat arrow) to prevent this behavior if we want. By using => instead of –> we can define a function to the current value of this.

I’ll round of this post by showing you the equivalent JavaScript code for the small class hierarchy shown in our example.

var podcast = {
    title: 'Astronomy Cast',
    description: 'A fact-based journey through the galaxy.',
    details: {
        homepage: 'http://www.astronomycast.com',
        rss: 'http://www.astronomycast.com/feed/',
        atom: 'http://www.astronomycast.com/feed/atom/'    
    },
    
    toString: function() {
       return 'Title: ' + this.title;
    }
};

Did I mention that every keystroke counts? ;-)

Until next time.
Profile picture of Jan Van Ryswyck

Jan Van Ryswyck

Thank you for visiting my blog. I’m a professional software developer since Y2K. A blogger since Y2K+5. Curator of the Awesome Talks list. Past organizer of the European Virtual ALT.NET meetings. Thinking and learning about all kinds of technologies since forever.

Comments

About

Thank you for visiting my website. I’m a professional software developer since Y2K. A blogger since Y2K+5. Curator of the Awesome Talks list. Past organizer of the European Virtual ALT.NET meetings. Thinking and learning about all kinds of technologies since forever.

Contact information

(+32) 496 38 00 82

infonull@nullprincipal-itnull.be