Home > Articles > Open Source > Ajax & JavaScript

CoffeeScript in a Nutshell, Part 4: Developing Applications

Parts 2 and 3 of Jeff Friesen's four-part series on CoffeeScript presented the language's basic and expression-oriented language features. Part 4 concludes the series by introducing you to classes and several additional language features: function binding, block regular expressions, closures, and embedded JavaScript.
Like this article? We recommend

Like this article? We recommend

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.

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020