CoffeeScript in a Nutshell, Part 4: Developing Applications
Part 3of 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 candownload 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 keywordthis, and they're used with the keywordnewto 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对象创建的方法是更多class-centric than JavaScript's. This approach begins with the keywordclass, which is used to define a new class. The following example usesclassto define a trivialEmployeeclass:
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 anEmployee()constructor function, which is subsequently returned via thereturnstatement. The returned function is assigned to anEmployeevariable, which represents the class.
You can instantiateEmployeevia thenewkeyword, 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 theconstructorkeyword. Simply assign a function to this property to perform the initialization, as follows:
class Employee constructor: (name) -> @name = name
The function assigned toEmployee's constructor identifies a singlenameparameter. This function assigns it to a same-namednameinstance property. The@prefix is shorthand forthis., 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 instantiateEmployeeand initialize itsnameproperty, 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 theconstructorkeyword once in the class definition.
Supporting Instance and Class Properties
Class-based languages identify instance and class (also known asstatic) 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 asalaryproperty parameter. It also initializes agetSalaryfunction property (a method) that returnssalary's value.
The JavaScript equivalent appears below:
员工=(函数(){员工(名称、年代alary) { 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 asEmployee).
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 fromnumEmployees, and.prototypehas been included when referencingnumEmployees. 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 specifiedEmployee.prototype.numEmployees = 5, each ofemp1.numEmployeesandemp2.numEmployeeswould return5.
Achieving Privacy
I previously specifiedsalaryandnumEmployeesproperties that can be accessed directly. However, it should be possible to access them only via thegetSalary()andgetNumEmployees()methods.
CoffeeScript provides some support for privacy. Specifically, you can hide instance field and instance method properties bynotprefixing the property name and specifying=after this name. This technique is demonstrated below:
class PrivacyDemo x = 1 foo = -> console.log "private method"
如果你试图访问x, as inpd.x,undefinedis returned. If you attempt to invokefoo(), as inpd.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 keywordsextendsandsuper. Consider the followingEmployeeclass and itsAccountantsubclass:
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 thesupercall is translated into a function call on the class's家长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());
InPart 3, I showed how to use aforcomprehension 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 firstforcomprehension returns all properties defined on thederivedobject and its prototype. The secondforcomprehension includes the keywordownto 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 theforandfor owncomprehensions 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 keywordthisto 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 ofthisis lost.
CoffeeScript provides the fat arrow (=>) for defining a function and binding it to the current value ofthis. These functions can access the properties ofthiswherever 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:
Click here to observe thin arrow result.
Click here to observe fat arrow result.
当执行这个例子,首先观察一个pair of alert dialog boxes displayingsmokey growls. Click onClick here to observe thin arrow result.and you observeundefined undefined. Click onClick here to observe fat arrow result.and you observesmokey growls.
If you investigate the equivalent JavaScript code (see below), you'll observethis.speak2 = __bind(this.speak2, this);in the constructor equivalent. This code is responsible for bindingspeak2()to the current value ofthis:
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 toCoffeeScript.org, ablock regular expressionis "an extended regular expression that ignores internal whitespace and can contain comments and interpolation."
Block regular expressions are modeled after Perl's/xmodifier 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 variablerereferences aRegExpobject. You can invoke this object'stest(string)确定方法的参数的方法matches the regular expression. The method returns true when there's a match.
Closures
CoffeeScript supports closures, where (according toWikipedia) aclosureis "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 calledfree variables) of that function."
CoffeeScript supports closures via thedokeyword, 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'sforcomprehension generates an array of functions:->signifies the function being generated. Each function outputs the value ofi. Instead of outputting this variable's value when the function was created (such asi = 0ori = 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, soicontains the final loop value (4) because the loop terminates whenicontains this value.
To solve this problem, insertdo(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->followingdo(i)generates a closure to close over loop variablei. You can observe this closure in the following JavaScript equivalent, where I'veboldfacedthe 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 afactorial()function that's defined in JavaScript. This function uses recursion to calculaten!(factorial). The recursion stops whenncontains0(0!equals1).
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 outCoffeeScript.org.