Home>Articles>Open Source>Ajax & JavaScript

CoffeeScript in a Nutshell, Part 4: Developing Applications

Parts 2and3of 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 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.

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, simplyemailinformation@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 ourContact Us form.

Other Collection and Use of Information


Application and System Logs

皮尔森自动收集日志数据来帮助sure 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 theAccount page. If a user no longer desires our service and desires to delete his or her account, please contact us atcustomer-service@informit.comand 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.e-skidka.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 toNevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read ourSupplemental privacy statement for California residentsin conjunction with this Privacy Notice. TheSupplemental privacy statement for California residentsexplains 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


Pleasecontact usabout this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


我们可以修改这个隐私通过updat通知ed 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