JavaScript Starter KitThe Tools You Need to Get Started with JavaScript “JavaScript is now a language every developer should know.” – Mike Loukides, Vice President of Content Strategy f
Trang 1Where We’ve Been, Where We Are, and What Lies Ahead
Dr Axel Rauschmayer
The Past, Present, and Future of
JavaScript
Trang 2JavaScript Starter Kit
The Tools You Need to Get Started with JavaScript
“JavaScript is now a language
every developer should know.”
– Mike Loukides, Vice President of Content Strategy for O’Reilly Media
Buy any two titles
and get the 3rd Free.
Use discount code: OPC10
Or, buy them all for
Use discount code: JSSKT
Trang 3The Past, Present, and Future of JavaScript
Axel Rauschmayer
Beijing • Cambridge • Farnham • Köln • Sebastopol • Tokyo
Trang 4The Past, Present, and Future of JavaScript
by Axel Rauschmayer
Copyright © 2012 Axel Rauschmayer All rights reserved.
Printed in the United States of America.
Published by O’Reilly Media, Inc., 1005 Gravenstein Highway North, Sebastopol,
CA 95472.
O’Reilly books may be purchased for educational, business, or sales promotional use Online editions are also available for most titles (http://my.safaribookson line.com) For more information, contact our corporate/institutional sales depart- ment: 800-998-9938 or corporate@oreilly.com.
Editor: Mac Slocum
Production Editor: Melanie Yarbrough Cover Designer: Karen Montgomery
Interior Designer: David Futato
Illustrator: Robert Romano July 2012: First Edition
Revision History for the First Edition:
2012-07-20 First release
See http://oreilly.com/catalog/errata.csp?isbn=9781449339968 for release details.
Nutshell Handbook, the Nutshell Handbook logo, and the O’Reilly logo are
regis-tered trademarks of O’Reilly Media, Inc The Past, Present, and Future of
Java-Script and related trade dress are trademarks of O’Reilly Media, Inc.
Many of the designations used by manufacturers and sellers to distinguish their products are claimed as trademarks Where those designations appear in this book, and O’Reilly Media, Inc., was aware of a trademark claim, the designations have been printed in caps or initial caps.
While every precaution has been taken in the preparation of this book, the publisher and authors assume no responsibility for errors or omissions, or for damages re- sulting from the use of the information contained herein.
ISBN: 978-1-449-33996-8
1344364583
Trang 5JavaScript as a Compilation Target 28Writing Non-Web Applications in JavaScript 32
iii
Trang 7The Past, Present, and Future of
• “The Past” on page 1
• “The Present” on page 5
• “The Future” on page 6
We conclude with a wish list and a few parting thoughts
The Past
In 1995, Netscape’s Navigator was the dominant web browser and the pany decided to add interactivity to HTML pages, via a lightweight program-ming language They hired Brendan Eich to implement it He finished a firstversion of the language in 10 days, in May 1995 Its initial name was Mochawhich was changed to the more Netscape-esque LiveScript in September InDecember, Netscape and Sun had a licensing agreement that led to the pro-gramming language’s final name, JavaScript At that point, it was included inNetscape Navigator 2.0B3
com-The name “JavaScript” hints at the originally intended role for the language:Sun’s Java was to provide the large-scale building blocks for web applications,while JavaScript was to be the glue, connecting the blocks Obviously, thatshared client-side responsibility never transpired: JavaScript now dominatesthe browser, Java is mostly dead there
1
Trang 8JavaScript was influenced by several programming languages: The Lisp dialectScheme gave it its rules for variable scoping, including closures The Self pro-gramming language—a Smalltalk descendant—gave it prototypal inheritance(object-based as opposed to class-based).
Because JavaScript was supposed to support Java, Netscape management manded that its syntax be similar to Java’s That ruled out using other existingscripting languages such as Perl, Python or TCL However, even though Java-Script’s syntax is similar to Java’s, it is quite a different language.[1 on page 36]
de-Standardization
After JavaScript came out, Microsoft implemented the same language, underthe different name JScript, in Internet Explorer 3.0 (August 1996) Netscapedecided to standardize JavaScript and asked the standards organization EcmaInternational to host the standard Work on a specification called ECMA-262started in November 1996 The first edition of ECMA-262 came out in June
1997 Because Sun (now Oracle) had a trademark on the word Java, the guage to be standardized couldn’t be called JavaScript Hence, the followingnaming was chosen: ECMAScript is the name of the standard language, itsimplementations are officially called JavaScript, JScript, etc Naturally, whentalking unofficially about either the standard or its implementations, onemostly uses the term JavaScript The current version of ECMAScript is 5.1,which means the same as ECMA-262, edition 5.1 That version has also be-come an ISO standard: ISO/IEC 16262:2011
lan-ECMA-262 is managed and evolved by Ecma’s Technical Committee 39
(short: TC39) Its members are companies such as Microsoft, Mozilla, orGoogle, which appoint employees to participate in committee work—threenames among several: Brendan Eich, Allen Wirfs-Brock (editor of ECMA-262)and David Herman TC39’s work includes discussing the design of upcomingversions via open channels such as a mailing list
Reaching consensus and creating a standard is not always easy, but thanks to
it, JavaScript is a truly open language, with implementations by multiple dors that are remarkably compatible That compatibility is made possible by
ven-a very detven-ailed ven-and concrete specificven-ation For exven-ample, it often uses code to specify things The specification is complemented by a test suite called
pseudo-test262 that checks an ECMAScript implementation for compliance It is teresting to note that ECMAScript is not managed by the World Wide WebConsortium (W3C) TC39 and the W3C collaborate wherever there is overlapbetween JavaScript and HTML5
Trang 9in-Historic JavaScript Milestones
It took JavaScript a long time to make an impact Many technologies existedfor a while until they were discovered by the mainstream This section de-scribes what happened since JavaScript’s creation until today Throughout,only the most popular projects are mentioned and many are ignored, even ifthey were first Two examples: the Dojo Toolkit is listed, but there is also thelesser-known qooxdoo, which was created around the same time And Node.js
is listed, even though Jaxer existed before it
1997— Dynamic HTML Dynamic HTML allows one to dynamically change
the content and appearance of a web page That is achieved by manipulatingthe Document Object Model (DOM) of the page: changing content, changingstyle, showing and hiding elements, etc Dynamic HTML appeared first inInternet Explorer 4 and in Netscape Navigator 4
1999— XMLHttpRequest This API lets a client-side script send an HTTP or
HTTPS request to a server and get back data, usually in a text format (XML,HTML, JSON) It was introduced in Internet Explorer 5
2001— JSON , a JavaScript-based data exchange format In 2001, Douglas
Crockford named and documented JSON (JavaScript Object Notation)—aLisp-like idea to use JavaScript syntax to store data in text format JSON usesJavaScript literals for objects, arrays, strings, numbers, and booleans to rep-resent structured data Example:
2004— Dojo Toolkit , a framework for programming JavaScript in the large The Dojo Toolkit facilitates programming in the large by providing the
necessary infrastructure: an inheritance library, a module system, an API fordesktop-style graphical widgets, etc
The Past | 3
Trang 102005— Ajax , browser-based desktop-class applications Ajax is a
collec-tion of technologies that brings a level of interactivity to web pages that rivalsthat of desktop applications One impressive example of what can be achievedvia Ajax was introduced in February 2005: Google Maps You were able topan and zoom over a map of the world, but only the content that was currentlyvisible was downloaded to the browser After Google Maps came out, JesseJames Garrett noticed that it shared certain traits with other interactive web-sites He called these traits “Ajax,” an acronym for Asynchronous JavaScriptand XML The two cornerstones of Ajax are: First, loading content asynchro-nously in the background (via XMLHttpRequest) Second, dynamically up-dating the current page with the results (via dynamic HTML) That was aconsiderable usability improvement from always performing complete pagereloads
Ajax marked the mainstream breakthrough of JavaScript and dynamic webapplications It is interesting to note how long that took—at that point, theAjax ingredients had been available for years Since the inception of Ajax, otherdata formats have become popular (JSON instead of XML), other protocolsare used (e.g., Web Sockets in addition to HTTP) and bi-directional commu-nication is possible But the basic techniques are still the same However, theterm Ajax is used much less these days and has mostly been replaced by themore comprehensive term HTML5 (JavaScript plus browser APIs)
2005— Apache CouchDB , a JavaScript-centric database Roughly,
CouchDB is a JSON database: You feed it JSON objects, without the need tospecify a schema in advance Additionally, you can define views and indexesvia JavaScript functions that perform map/reduce operations Hence,CouchDB is a very good fit for JavaScript because you can directly work withnative data Compared to a relational database, there is no mapping-relatedimpedance mismatch Compared to an object database, you avoid many com-plications because only data is stored, not behavior CouchDB is just one ofseveral similar “NoSQL” databases Most of them have excellent JavaScriptsupport
2006— jQuery , helping with DOM manipulation The browser DOM
(Document Object Model) is one of the most painful parts of client-side webdevelopment jQuery made DOM manipulation fun by abstracting overbrowser differences and by providing a powerful fluent-style API for queryingand modifying the DOM
2007— WebKit becomes the foundation of the mobile web Based on prior
work by KDE, WebKit is an HTML engine that was introduced by Apple in
2003 It was open-sourced in 2005 With the introduction of the iPhone in
2007, it became the foundation of the mobile web WebKit is now the main
engine for Android and the only engine for iOS, and dominates the mobile
Trang 11market That means if you want to write a cross-platform mobile application,then web technology is currently your best bet (unless you need features thatare only available natively).
2008— V8 , JavaScript can be fast When Google introduced its Chrome
web browser, one of its highlights was a fast JavaScript engine called V8 Itchanged the perception of JavaScript as being slow and led to a speed race withother browser vendors that we are still profiting from V8 is open source andcan be used as a stand-alone component whenever one needs a fast embeddedlanguage that is widely known
2009— Node.js , JavaScript on the server Node.js lets you implement
servers that perform well under load To do so, it uses event-driven blocking I/O and JavaScript (via V8) Node.js creator Ryan Dahl mentions thefollowing reasons for choosing JavaScript:
non-• “Because it’s bare and does not come with I/O APIs.” [Node.js can thusintroduce its own non-blocking APIs.]
• “Web developers use it already.” [JavaScript is a widely known language,especially in a web context.]
• “DOM API is event-based Everyone is already used to running withoutthreads and on an event loop.” [Web developers are not scared of call-backs.]
Dahl was able to build on prior work on event-driven servers and server-sideJavaScript (mainly the CommonJS project)
The appeal of Node.js for JavaScript programmers goes beyond being able toprogram in a familiar language; you get to use the same language on both clientand server That allows you to do clever things such as a fallback for browsersthat don’t run sufficiently sophisticated versions of JavaScript: Assemble thepages on the server—with the same code that you are using on JavaScript-enabled clients (examples: FunctionSource’s web server, Yahoo Cocktails)
The Present | 5
Trang 12also makes it possible to use JavaScript for build scripts and shell scripts.Lastly, JavaScript is possibly the most open programming language there is:
no single party controls it, there is a well-written specification for it (whosevalue cannot be overestimated), and there are several highly compatible im-plementations available
The Future
The future brings many exciting developments for JavaScript: Script.next will fix quirks and add new features It will also be a better targetlanguage for compilers Support for concurrency is important and several op-tions for JavaScript are currently being evaluated Finally, HTML5 is becoming
ECMA-a compelling plECMA-atform, not just for web ECMA-applicECMA-ations, but ECMA-also for mobile ECMA-plications and desktop applications
ap-Evolving the Language
After ECMAScript 3, there was a period where TC39 was divided on how toevolve the language A meeting in August 2008 resolved the division Theagreement was to develop both an incremental update (which eventually be-came ECMAScript 5) and major new language features Those features werecode-named Harmony, due to the nature of the meeting ECMAScript Har-mony is too large in scope to fit into a single version Hence, there is anothercode name, ECMAScript.next, for the next version of ECMAScript ECMA-Script.next will probably become ECMAScript 6 Harmony’s requirementsand goals are described as follows on the ECMAScript wiki [2 on page 36]:Requirements:
• New features require concrete demonstrations
• Keep the language pleasant for casual developers
• Preserve the “start small and iteratively prototype” nature of the language.Goal 1 (of several) is for ECMAScript Harmony to “be a better language forwriting ”
a complex applications;
b libraries (possibly including the DOM) shared by those applications;
c code generators targeting the new edition
How features are added to ECMAScript.next
The process for adding a new feature to the standard is as follows First, aproposal for the feature is written, by a “champion”, an expert in the relevant
Trang 13domain That avoids some of the dangers of “design by committee” Next,promising proposals are field-tested via prototype implementations in one ormore browsers If the feature proves itself, its specification is added to theECMAScript.next draft [3 on page 36] Naturally, while taking feedbackfrom the field test into account.
The following sections describe several ECMAScript.next proposals Some ofthem are likely to be included (e.g let), others are still under discussion (e.g.,class declarations, more number types) Until the projected completion ofECMAScript.next at the end of 2013, nothing is set in stone Features mightchange or TC39 might consider ECMAScript.next as having become too largeand discard features
Block scoping via let and const
In current JavaScript, variables are function-scoped—if you declare a variablevia var, it exists within all of the innermost function that surrounds it In thefollowing example, tmp is not confined to the then-block:
Trang 14Handling parameters, assignment
ECMAScript.next will make the special variable arguments obsolete Instead,one will be able to use parameter default values and rest parameters:
// Parameter default values
function foo(mandatory, optional1=123, optional2="abc") { }
// Rest parameters
function bar(arg1, remainingArguments) { }
Assignment can be destructuring, it can extract values from the right-handside, via a simple form of pattern matching:
// Swap the values of a and b
Trang 15non-let jane = {
name: "Jane",
The Future | 9
Trang 16logHello: function (friends) {
var that = this; // (*)
let func = (a, b) => { return this.offset + a + b }
let func = function (a, b) { return this.offset + a + b }.bind(this);
The body of an arrow function can also be an expression, making code muchmore readable Compare:
let squares = [ 1, 2, 3 ].map(function (x) { return x * x });
let squares = [ 1, 2, 3 ].map(x => x * x);
Trang 17Object literals
There are several proposals for constructs that help with JavaScript orientation Object literals will get a large upgrade:
object-let name = "foo";
let obj = MyProto <| { // "prototype for" operator
myMethod(arg1, arg2) { // method definition
super.myMethod(arg1, arg2); // super reference
},
[name]: 123, // computed property key
bar // property value shorthand
}
Features shown above:
Prototype-for operator (<|) lets you specify the prototype of a literal, which
is certainly more convenient than Object.create() And it mostly obviates theneed for the special property proto which is non-standard andproblematic
Method definitions can be made via a shorter syntax.
Super-references let you refer to a property appearing later in the prototype
chain The search for such a property starts in the prototype of the object wherethe method is located Note that this way of referring to super-properties worksfor both subtypes (where one can, e.g., refer to a method of the supertype thathas been overridden) and directly constructed prototype chains
Computed property keys are a way to specify the name of a property via an
expression (which is especially useful for private name objects—see below)
A property value shorthand eliminates some redundancy when filling an
object literal with data bar is an abbreviation for
Trang 18Object extension literals
With super-references, a method is much tighter bound to the object it is stored
in and needs to have a reference to it The method definition syntax abovetakes care of that and is thus the preferred way of creating methods An objectextension literal ensures that this syntax can also be used to add methods to
an existing object Example:
Private name objects
If you want to keep data private in JavaScript, you currently have two mainoptions: You can either put it into the environment of the constructor, or youcan keep it in properties with special names (e.g starting with an underscore).Using the environment of the constructor means that only methods that areadded there can access private data, but not, say, “public” methods in the
Trang 19prototype To do so, they need “privileged” methods that have been added tothe instance in the constructor.
The following example is not realistic, but it illustrates how
MyType.prototype.multiply = function (value) {
return this.getFactor() * value;
};
The following code is similar, but keeps the private data in the property
_factor The name starting with an underscore marks that property as private.The problem with this approach is that such properties occupy the samenamespace as public properties and pollute it, when they should be hidden.And the private data is not safe from outside access
MyType.prototype.multiply = function (value) {
return this._factor * value;
};
The Future | 13
Trang 20The proposal “private name objects” for ECMAScript.next combines the vantages of both approaches and works as follows Currently, property nameshave to be strings The proposal additionally allows one to use name objectsthat have to be explicitly created and are unique and unforgeable:
ad-import Name from "@name";
let factorKey = new Name(); // create private name object
MyType.prototype.multiply = function (value) {
return this[factorKey] * value;
};
The property whose name is the name object factorKey cannot be found viaany enumeration mechanism (Object.getOwnPropertyNames(), for in, etc.).And one can only access its value if one has its name Hence, there is no name-space pollution and the private data is safe
Class declarations
Implementing single types via constructor functions is reasonably easy in Script, but subtyping is too complicated and making super-references isclumsy
Java-Right now, you have to write:
Trang 22import 'http://json.org/modules/json2.js' as JSON;
import { add, sub } from Math;
export const HELLO_STRING = JSON.stringify({ hello: 'world' });
export function total( args) {
args.reduce((prevResult, elem) => add(prevResult, elem));
}
ECMAScript.next modules are more static than module systems implemented
in JavaScript That enables benefits such as better performance, pre-fetching,and compile-time checking (find unbound variables etc.)
Loops and iteration
One can use the for in loop to iterate over objects However, that loop hasseveral quirks ECMAScript.next will introduce a new iteration infrastruc-ture, including a for of loop that fixes the for in quirks For example, ititerates over the elements of an array, not over the property names:
let arr = [ "hello", "world" ];
for (let elem of arr) {