Be careful declaring properties in CoffeeScript

In JavaScript, if you set a property on the prototype, it is like a static property that is shared by all instances of the Function. This is common knowledge in JavaScript and quite visible in the code. However if you are writing all your code in CoffeeScript, this fact gets hidden away by the way you declare properties.

1 class Site extends Backbone.view
2   staticProp: "hello"
3 
4   initialize: ->
5     @instanceProp: "instance hello"

If you declare properties without the @ symbol, you are effectively creating properties on the prototype of the class. This of course works great if you want a shared property but certainly not the way to go if you want per-instance properties. I missed out using the @ symbol and my app went bonkers. This simple oversight cost me fair bit of time debugging it. The right thing to do was using the @property syntax, since I needed per-instance properties. In the code snippet shown above, the staticProp is a property on the prototype of the Site function. @instanceProp is an instance property that will be available on each instance of Site. CoffeeScript translates the above source to the following JavaScript:

 1 var Site;
 2 var __hasProp = Object.prototype.hasOwnProperty, __extends = function(child, parent) {
 3   for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; }
 4   function ctor() { this.constructor = child; }
 5   ctor.prototype = parent.prototype;
 6   child.prototype = new ctor;
 7   child.__super__ = parent.prototype;
 8   return child;
 9 };
10 Site = (function() {
11   __extends(Site, Backbone.view);
12   function Site() {
13     Site.__super__.constructor.apply(this, arguments);
14   }
15   Site.prototype.staticProp = "hello";
16   Site.prototype.initialize = function() {
17     return {
18       this.instanceProp: "instance hello"
19     };
20   };
21   return Site;
22 })();

As you can see, staticProp (line# 15)is set on the Site.prototype and instanceProp (line# 18) is on the instance (this) of Site. So the take away is:

Be careful while declaring properties in CoffeeScript

CoffeeScript offers a lot of syntax sugar which makes programming JavaScript a lot more fun. Do check out the website for other interesting features.