Mindful of CoffeeScript Function Return Value

Here’s a gotcha if you’re not careful when writing CoffeeScript. Notice the generated js code where constructor now returns this._cursor!!

#c.coffee
Cursor = (cursor) ->
  this._cursor = cursor
0 // c.js
1 // Generated by CoffeeScript 1.6.2
2 (function() {
3   var Cursor;
4
5   Cursor = function(cursor) {
6     return this._cursor = cursor;
7   };
8
9 }).call(this);

Here’s the fix.

#c.coffee
Cursor = (cursor) ->
  this._cursor = cursor
  this
0 // c.js
1 // Generated by CoffeeScript 1.6.2
2 (function() {
3   var Cursor;
4
5   Cursor = function(cursor) {
6     this._cursor = cursor;
7     return this;
8   };
9
10 }).call(this);

About rp8

Specialized in building sophisticated systems for trading & risks in commodity, exotics, commodity index & structured products. Specially interested in using open source stacks and cloud computing to build new generation of services and apps. Enjoy mountain biking & photography. github
This entry was posted in General, JavaScript and tagged . Bookmark the permalink.