Site Logo

Pixel-in-Gene

Exploring Frontend Development with Design / Graphics / Technology

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.

class Site extends Backbone.view
  staticProp: "hello"

  initialize: ->
    @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:

var Site;
var __hasProp = Object.prototype.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;
};
Site = (function() {
  __extends(Site, Backbone.view);
  function Site() {
    Site.__super__.constructor.apply(this, arguments);
  }
  Site.prototype.staticProp = "hello";
  Site.prototype.initialize = function() {
    return {
      this.instanceProp: "instance hello"
    };
  };
  return Site;
})();

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.

Be careful declaring properties in CoffeeScript
Pavan Podila
Pavan Podila
August 25th, 2011