CoffeeScript in a Nutshell, Part 4: Developing Applications
Part 3 of this four-part series on the CoffeeScript programming language introduced you to CoffeeScript's expression-oriented features. You learned that almost everything is an expression, and we explored new operators, improved operators, destructuring assignments, decisions, and loops. This article concludes this series by exploring classes and a few other CoffeeScript features. You can download the code from this article here.
Classes
Many developers who are exposed to the class-based approach for creating objects are confused by JavaScript's prototype-based approach, which avoids classes. Their confusion typically centers on the following pair of concepts:
- Constructor functions. These functions add properties to empty objects via the keyword this, and they're used with the keyword new to instantiate these objects. (See "Constructor Functions" for details.)
- Prototype inheritance. This feature involves different objects sharing the same properties via constructor function prototypes. (See "JavaScript Object Prototype" for details.)
Defining Classes and Instantiating Objects
CoffeeScript's approach to object creation is more class-centric than JavaScript's. This approach begins with the keyword class, which is used to define a new class. The following example uses class to define a trivial Employee class:
class Employee
CoffeeScript's compiler translates this definition into the following JavaScript code:
Employee = (function() { function Employee() {} return Employee; })();
This code reveals a closure that first defines an Employee() constructor function, which is subsequently returned via the return statement. The returned function is assigned to an Employee variable, which represents the class.
You can instantiate Employee via the new keyword, as follows:
emp = new Employee
The JavaScript equivalent appears below:
emp = new Employee;
Constructing Objects
In a class-based language, you use a constructor to initialize an object. JavaScript supplies constructor functions for this purpose. CoffeeScript bridges the gap by supplying the constructor keyword. Simply assign a function to this property to perform the initialization, as follows:
class Employee constructor: (name) -> @name = name
The function assigned to Employee's constructor identifies a single name parameter. This function assigns it to a same-named name instance property. The @ prefix is shorthand for this., which the following equivalent JavaScript code reveals:
Employee = (function() { function Employee(name) { this.name = name; } return Employee; })();
CoffeeScript offers a shorthand notation for setting instance properties. Prefix a parameter name with @ and CoffeeScript automatically assigns it to a same-named instance property. Consider the following example:
class Employee constructor: (@name) ->
The resulting JavaScript code is identical to the previous JavaScript code.
You can now instantiate Employee and initialize its name property, as follows:
emp = new Employee "John" console.log emp.name # output: John
Unlike in a class-based language, CoffeeScript supports only one constructor per class. Therefore, you can only use the constructor keyword once in the class definition.
Supporting Instance and Class Properties
Class-based languages identify instance and class (also known as static) fields: Instance fields belong to class instances (objects), and class fields belong to classes. They also identify instance and class methods; instance methods access instance fields and class methods access class fields.
CoffeeScript supports instance fields, instance methods, class fields, and class methods. Instance fields and instance methods are supported via properties that are initialized in the constructor, as demonstrated below:
class Employee constructor: (@name, @salary) -> @getSalary = -> salary emp = new Employee "John", 30000 console.log emp.name # output: John console.log emp.salary # output: 30000 console.log emp.getSalary() # output: 30000
Employee's constructor has been expanded to include a salary property parameter. It also initializes a getSalary function property (a method) that returns salary's value.
The JavaScript equivalent appears below:
Employee = (function() { function Employee(name, salary) { this.name = name; this.salary = salary; this.getSalary = function() { return this.salary; }; } return Employee; })(); emp = new Employee("John", 30000); console.log(emp.name); console.log(emp.salary); console.log(emp.getSalary());
Class fields and class methods are also supported via properties, which must be prefixed with @ and initialized in the class. Also, when accessing a class-based property, you must prefix it with the class name and a period character. Consider the following example:
class Employee @numEmployees: 0 constructor: (@name) -> Employee.numEmployees++ @getNumEmployees: -> Employee.numEmployees emp = new Employee "John" emp = new Employee "Jane" console.log Employee.numEmployees # output: 2 console.log Employee.getNumEmployees() # output: 2
Instead of specifying @numEmployees: 0, I could have achieved the same result by specifying @numEmployees = 0. The JavaScript equivalent follows:
Employee = (function() { Employee.numEmployees = 0; function Employee(name) { this.name = name; Employee.numEmployees++; } Employee.getNumEmployees = function() { return Employee.numEmployees; }; return Employee; })(); emp = new Employee("John"); emp = new Employee("Jane"); console.log(Employee.numEmployees); console.log(Employee.getNumEmployees());
Unlike instance properties initialized in the constructor, which are stored in the object being created (for example, new Employee("John")), class properties are stored in the class object from which objects are created (such as Employee).
CoffeeScript supports a variation of class properties: prototype properties. By omitting @ from a property definition (as in @numEmployees: 0), the property is stored in the class object's prototype instead of in the class object. Consider this example:
class Employee numEmployees: 0 constructor: (@name) -> Employee.prototype.numEmployees++ @getNumEmployees: -> Employee.prototype.numEmployees emp1 = new Employee "John" emp2 = new Employee "Jane" console.log Employee.prototype.numEmployees # output: 2 console.log Employee.getNumEmployees() # output: 2
This example differs from its predecessor in two ways: The @ prefix has been removed from numEmployees, and .prototype has been included when referencing numEmployees. Check out the following JavaScript equivalent:
Employee = (function() { Employee.prototype.numEmployees = 0; function Employee(name) { this.name = name; Employee.prototype.numEmployees++; } Employee.getNumEmployees = function() { return Employee.prototype.numEmployees; }; return Employee; })(); emp1 = new Employee("John"); emp2 = new Employee("Jane"); console.log(Employee.prototype.numEmployees); console.log(Employee.getNumEmployees());
A prototype property is shared by all class instances. When any instance changes this property, all instances can see the change. For example, if I specified Employee.prototype.numEmployees = 5, each of emp1.numEmployees and emp2.numEmployees would return 5.
Achieving Privacy
I previously specified salary and numEmployees properties that can be accessed directly. However, it should be possible to access them only via the getSalary() and getNumEmployees() methods.
CoffeeScript provides some support for privacy. Specifically, you can hide instance field and instance method properties by not prefixing the property name and specifying = after this name. This technique is demonstrated below:
class PrivacyDemo x = 1 foo = -> console.log "private method"
If you try to access x, as in pd.x, undefined is returned. If you attempt to invoke foo(), as in pd.foo(), the compiler reports an error.
The following JavaScript code shows how privacy is achieved:
PrivacyDemo = (function() { var foo, x; function PrivacyDemo() {} x = 1; foo = function() { return console.log("private method"); }; return PrivacyDemo; })();
Privacy is achieved by introducing local variables into the closure. You cannot access these variables from beyond the closure (that is, the class).
Supporting Inheritance
CoffeeScript provides support for inheritance by offering the keywords extends and super. Consider the following Employee class and its Accountant subclass:
class Employee constructor: (@name) -> @getName = -> name class Accountant extends Employee constructor: (name) -> super name acct = new Accountant "John" console.log acct.getName() # output: John
The following JavaScript equivalent (somewhat modified for readability) shows that the super call is translated into a function call on the class's parent prototype; the call occurs in the current context:
__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; }; Employee = (function() { function Employee(name) { this.name = name; this.getName = function() { return name; }; } return Employee; })(); Accountant = (function(_super) { __extends(Accountant, _super); function Accountant(name) { Accountant.__super__.constructor.call(this, name); } return Accountant; })(Employee); acct = new Accountant("John"); console.log(acct.getName());
In Part 3, I showed how to use a for comprehension to iterate over an object literal's keys and values. You can also use this technique to iterate over an object's properties, as follows:
class Base constructor: -> @a = 1 class Derived extends Base constructor: -> super @b = 2 derived = new Derived console.log "#{name}: #{value}" for name, value of derived console.log "" console.log "#{name}: #{value}" for own name, value of derived
The first for comprehension returns all properties defined on the derived object and its prototype. The second for comprehension includes the keyword own to ignore prototype properties. You see the following output:
a: 1 b: 2 constructor: function Derived() { Derived.__super__.constructor.apply(this, arguments); this.b = 2; } a: 1 b: 2
The following JavaScript code fragment shows how the for and for own comprehensions are implemented:
for (name in derived) { value = derived[name]; console.log("" + name + ": " + value); } console.log(""); for (name in derived) { if (!__hasProp.call(derived, name)) continue; value = derived[name]; console.log("" + name + ": " + value); }
Function Binding
JavaScript dynamically scopes the keyword this to identify the object to which the current function is attached. If you pass a callback function or attach the function to a different object, the original value of this is lost.
CoffeeScript provides the fat arrow (=>) for defining a function and binding it to the current value of this. These functions can access the properties of this wherever they're defined. This capability is helpful when working with jQuery and other callback-based libraries.
The following example contrasts the thin arrow (->) with the fat arrow in a jQuery context:
<div id="div1" style="border: solid; text-align: center"> Click here to observe thin arrow result. </div> <p> <div id="div2" style="border: solid; text-align: center"> Click here to observe fat arrow result. </div> <script type="text/coffeescript"> class Animal constructor: (@name, @noise) -> speak1: -> alert "#{@name} #{@noise}" speak2: => alert "#{@name} #{@noise}" bear = new Animal "smokey", "growls" bear.speak1() bear.speak2() $("#div1").click(bear.speak1) $("#div2").click(bear.speak2) </script>
When this example executes, you first observe a pair of alert dialog boxes displaying smokey growls. Click on Click here to observe thin arrow result. and you observe undefined undefined. Click on Click here to observe fat arrow result. and you observe smokey growls.
If you investigate the equivalent JavaScript code (see below), you'll observe this.speak2 = __bind(this.speak2, this); in the constructor equivalent. This code is responsible for binding speak2() to the current value of this:
var Animal, __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; }; Animal = (function() { var bear; function Animal(name, noise) { this.name = name; this.noise = noise; this.speak2 = __bind(this.speak2, this); } Animal.prototype.speak1 = function() { return alert("" + this.name + " " + this.noise); }; Animal.prototype.speak2 = function() { return alert("" + this.name + " " + this.noise); }; bear = new Animal("smokey", "growls"); bear.speak1(); bear.speak2(); $("#div1").click(bear.speak1); $("#div2").click(bear.speak2); return Animal; })();
Block Regular Expressions
CoffeeScript supports block regular expressions to improve the readability of complex regular expressions. According to CoffeeScript.org, a block regular expression is "an extended regular expression that ignores internal whitespace and can contain comments and interpolation."
Block regular expressions are modeled after Perl's /x modifier and delimited by ///. They're very helpful in improving the readability of complex regular expressions. The following example demonstrates a block regular expression:
re = /// (\(\d{3}\))? # area code \s* # spaces \d{3}-\d{4} # number ///
This example specifies a multiline block regular expression for matching phone numbers of the form ddd-dddd or (ddd) ddd-dddd. The JavaScript equivalent appears below:
re = /(\(\d{3}\))?\s*\d{3}-\d{4}/;
The variable re references a RegExp object. You can invoke this object's test(string) method to determine whether the method's argument matches the regular expression. The method returns true when there's a match.
Closures
CoffeeScript supports closures, where (according to Wikipedia) a closure is "a function or reference to a function together with a referencing environment—a table storing a reference to each of the non-local variables (also called free variables) of that function."
CoffeeScript supports closures via the do keyword, which inserts a closure wrapper. This wrapper is used to ensure that a loop variable is closed over so that no generated functions share the final value of this variable when generating functions in a loop.
The following example creates a four-element array of functions that are supposed to serve as closures:
closures = []; makeClosures = -> closures = for i in [0..3] -> console.log "i = #{i}" run = -> closures[i]() for i in [0..3] makeClosures() run()
This example's for comprehension generates an array of functions: -> signifies the function being generated. Each function outputs the value of i. Instead of outputting this variable's value when the function was created (such as i = 0 or i = 2), the following output is generated:
i = 4 i = 4 i = 4 i = 4
Unfortunately, the function doesn't close over the loop variable, so only the final value of this variable is output when the function runs—it isn't a true closure. This is proven by the following equivalent JavaScript code:
closures = []; makeClosures = function() { var i; return closures = (function() { var _i, _results; _results = []; for (i = _i = 0; _i <= 3; i = ++_i) { _results.push(function() { return console.log("i = " + i); }); } return _results; })(); }; run = function() { var i, _i, _results; _results = []; for (i = _i = 0; _i <= 3; i = ++_i) { _results.push(closures[i]()); } return _results; }; makeClosures(); run();
Here, function() { return console.log("i = " + i); } isn't wrapped in a closure, so i contains the final loop value (4) because the loop terminates when i contains this value.
To solve this problem, insert do(i) -> in front of -> console.log "i = #{i}", as follows:
closures = [] makeClosures = -> closures = for i in [0..3] do(i) -> -> console.log "i = #{i}" makeClosures() run()
The -> following do(i) generates a closure to close over loop variable i. You can observe this closure in the following JavaScript equivalent, where I've boldfaced the closure:
closures = []; makeClosures = function() { var i; return closures = (function() { var _i, _results; _results = []; for (i = _i = 0; _i <= 3; i = ++_i) { _results.push((function(i) { return function() { return console.log("i = " + i); }; })(i)); } return _results; })(); }; makeClosures(); run();
When this example is run, it produces the following output:
i = 0 i = 1 i = 2 i = 3
Embedded JavaScript
Suppose you've created a lot of JavaScript code that you want to use in a CoffeeScript application, but you don't want to take the time to translate from JavaScript to CoffeeScript. You can accomplish this task by placing the JavaScript code between a pair of backticks (`), as follows:
`function factorial(n) { if (n === 0) return 1; else return n*factorial(n-1); }` result = factorial 5 console.log "5! = #{result}" # output: 5! = 120
This example introduces a factorial() function that's defined in JavaScript. This function uses recursion to calculate n! (factorial). The recursion stops when n contains 0 (0! equals 1).
The compiler's translation to JavaScript code appears below, and shows that the JavaScript code is unchanged:
// Generated by CoffeeScript 1.6.2 (function() { function factorial(n) { if (n === 0) return 1; else return n*factorial(n-1); }; var result; result = factorial(5); console.log("5! = " + result); }).call(this);
Conclusion
This article introduced you to CoffeeScript's support for classes, along with function binding, block regular expressions, closures, and embedded JavaScript. This completes my introduction to CoffeeScript and its various language features. To learn more about this remarkable language, check out CoffeeScript.org.