




























































































Estude fácil! Tem muito documento disponível na Docsity
Ganhe pontos ajudando outros esrudantes ou compre um plano Premium
Esta página não é visível na pré-visualização
Não perca as partes importantes!





























































































Programming JavaScript Applications by Eric Elliott
Copyright © 2014 Eric Elliott. 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.safaribooksonline.com ). For more information, contact our corporate/ institutional sales department: 800-998-9938 or [email protected].
Editors: Simon St. Laurent and Meghan Blanchette Production Editor: Kara Ebrahim Copyeditor: Eliahu Sussman Proofreader: Amanda Kersey
Indexer: Lucie Haskins Cover Designer: Randy Comer Interior Designer: David Futato Illustrator: Rebecca Demarest
July 2014: First Edition
Revision History for the First Edition:
2014-06-25: First release
See http://oreilly.com/catalog/errata.csp?isbn=9781491950296 for release details.
Nutshell Handbook, the Nutshell Handbook logo, and the O’Reilly logo are registered trademarks of O’Reilly Media, Inc. Programming JavaScript Applications , the image of an argali, and related trade dress are trade‐ marks 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 author assume no responsibility for errors or omissions, or for damages resulting from the use of the information contained herein.
ISBN: 978-1-491-95029-
[LSI]
We’ll cover:
Who This Book Is For
You have some experience with JavaScript; at least a year or two working frequently with the language, but you want to learn more about how you can apply it specifically to developing robust web-scale or enterprise applications.
You know a thing or two about programming, but you have an insatiable thirst to learn more. In particular, you’d like to learn more about how to apply the powerful features that distinguish JavaScript from other languages, such as closures, functional program‐ ming, and prototypal inheritance (even if this is the first you’ve heard of them).
Perhaps you’d also like to learn about how to apply test-driven development (TDD) techniques to your next JavaScript challenge. This book uses tests throughout the code examples. By the time you reach the end, you should be in the habit of thinking about how you’ll test the code you write.
Who This Book Is Not For
This book covers a lot of ground quickly. It was not written with the beginner in mind, but if you need clarification, you might find it in JavaScript: The Good Parts , by Douglas Crockford (O’Reilly, 2008), JavaScript: The Definitive Guide , by David Flannagan (O’Reilly, 2011), or for help with software design patterns, the famous Gang of Four book (GoF), Design Patterns: Elements of Reusable Object-Oriented Software , by Erich Gamma, Richard Helm, Ralph Johnson, and John Vlissides (Addison-Wesley, 1994).
Google and Wikipedia can be handy guides to help you through, as well. Wikipedia is a fairly good reference for software design patterns.
If this is your first exposure to JavaScript, you would do well to study some introductory texts and tutorials before you attempt to tackle this book. My favorite is Eloquent Java‐ Script by Marijn Haverbeke (No Starch Press, 2011). Be sure to follow that up with
viii | Preface
JavaScript: The Good Parts , and pay special attention to Appendix A so that you can learn from the mistakes made by more experienced JavaScript developers.
Unit Testing
It’s difficult to overstate the importance of unit testing. Unit tests are used throughout this book. By the time you reach the end, you should be accustomed to seeing and writing them. As you practice the concepts you read about, start by writing the tests first. You’ll get a better understanding of the problem domain, and you’ll be forced to think through the design for your solution and the interface you create for it. Designing for unit tests also forces you to keep your code decoupled. The discipline of writing testable, decou‐ pled code will serve you well your entire career.
For a reference on unit tests and code style, see Appendix A.
Conventions Used in This Book
The following typographical conventions are used in this book:
Italic Indicates new terms, URLs, email addresses, filenames, and file extensions.
Constant width Used for program listings, as well as within paragraphs to refer to program elements such as variable or function names, databases, datatypes, environment variables, statements, and keywords.
Constant width bold Shows commands or other text that should be typed literally by the user.
Constant width italic Shows text that should be replaced with user-supplied values or by values deter‐ mined by context.
This icon signifies a tip, suggestion, or general note.
This icon indicates a warning or caution.
Preface | ix
Thanks
Thanks @JS_Cheerleader for encouragement and lots of great JavaScript links.
Thanks to Brendan Eich for his tireless work to drive JavaScript and the web forward. Thanks to the team at O’Reilly. To Simon St. Laurent, who immediately recognized the value of the book and provided a lot of encouragement along the way. To Brian McDo‐ nald, whose valuable feedback made this a much better book. To Meghan Blanchette for keeping the momentum alive. Thanks to the following individuals for their great technical feedback:
A special thank you to the people who have contributed to the open source projects written for this book, and to all of the open source contributors who make programming JavaScript applications a much better experience every single day. As software devel‐ opers, we are all standing on the shoulders of giants.
Preface | xi
In 2004, Google launched Gmail. Initially applauded because it promised users nearly infinite storage for their email, Gmail also brought a major revolution. Gone were the page refreshes. Under the hood, Gmail was taking advantage of the new Ajax technology, creating a single-page, fast, and responsive web application that would forever change the way that web applications are designed.
Since that time, web developers have produced nearly every type of application, in‐ cluding full-blown, cloud-based office suites (see Zoho.com), social APIs like Facebook’s JavaScript SDK, and even graphically intensive video games.
All of this is serving to prove Atwood’s Law: “Any application that can be written in JavaScript, will eventually be written in JavaScript.”
Advantages of JavaScript
JavaScript didn’t just luck into its position as the dominant client-side language on the Web. It is actually very well suited to be the language that took over the world. It is one of the most advanced and expressive programming languages developed to date. The following sections outline some of the features you may or may not be familiar with.
Just-in-time compiling: in modern browsers, most JavaScript is compiled, highly opti‐ mized, and executed like native code, so runtime performance is close to that of software written in C or C++. Of course, there is still the overhead of garbage collection and dynamic binding, so it is possible to do certain things faster; however, the difference is generally not worth sweating over until you’ve optimized everything else. With Node.js (a high-performance, evented, server-side JavaScript environment built on Google’s highly optimized V8 JavaScript engine), JavaScript apps are event driven and non‐ blocking, which generally more than makes up for the code execution difference be‐ tween JavaScript and less dynamic languages.
JavaScript has very rich object-oriented (OO) features. The JSON (JavaScript Object Notation) standard used in nearly all modern web applications for both communication and data persistence is a subset of JavaScript’s excellent object-literal notation.
JavaScript uses a prototypal inheritance model. Instead of classes, you have object pro‐ totypes. New objects automatically inherit methods and attributes of their parent object through the prototype chain. It’s possible to modify an object’s prototype at any time, making JavaScript a very flexible, dynamic language.
2 | Chapter 1: The JavaScript Revolution
Prototypal OO is so much more flexible than classical inheritance that it’s possible to mimic Java’s class-based OO and inheritance models in JavaScript virtually feature for feature, and in most cases, with less code. The reverse is not true.
Contrary to common belief, JavaScript supports features like encapsulation, polymor‐ phism, multiple inheritance, and composition. You’ll learn more about these topics in Chapter 3.
The JavaScript syntax should be immediately familiar to anybody who has experience with C-family languages, such as C++, Java, C#, and PHP. Part of JavaScript’s popularity is due to its familiarity, though it’s important to understand that JavaScript behaves very differently from all of these under the hood.
JavaScript’s object-literal syntax is so simple, flexible, and concise, it was adapted to become the dominant standard for client/server communication in the form of JSON, which is more compact and flexible than the XML that it replaced.
In JavaScript, objects are not a tacked-on afterthought. Nearly everything in JavaScript is an object, including functions. Because of that feature, functions can be used anywhere you might use a variable, including the parameters in function calls. That feature is often used to define anonymous callback functions for asynchronous operations, or to create higher order functions (functions that take other functions as parameters, return a func‐ tion, or both). Higher-order functions are used in the functional programming style to abstract away commonly repeated coding patterns, such as iteration loops or other in‐ struction sets that differ mostly in the variables or data they consume.
Good examples of functional programing include functions like .map(), .reduce(), and .forEach(). The Underscore.js library contains many useful functional utilities. For simplicity, we’ll be making use of Underscore.js in this book.
Inside the browser, everything runs in an event loop. JavaScript coders quickly learn to think in terms of event handlers, and as a result, code from experienced JavaScript developers tends to be well organized and efficient. Operations that might block pro‐ cessing in other languages happen concurrently in JavaScript.
If you click something, you want something to happen instantly. That impatience has led to wonderful advancements in UI design, such as Google Instant and the ground‐ breaking address lookup on The Wilderness Downtown. (“The Wilderness Downtown” is an interactive short film by Chris Milk set to the Arcade Fire song, “We Used To Wait.”
Advantages of JavaScript | 3
To see how these generally fit together, see Figure 1-1.
Figure 1-1. Infrastructure
Most of these components are self explanatory, but there are some important points that you should be aware of concerning the storage and communication of application data.
The data store is just like it sounds: a place to store your application data. This is com‐ monly a relational database management system (RDBMS) with a Structured Query Language (SQL) API, but the popularity of NoSQL solutions is on the rise. In the future, it’s likely that many applications will use a combination of both.
JavaScript Object Notation (JSON) is an open standard developed by Douglas Crock‐ ford that specifies a subset of the native JavaScript object-literal syntax for use in data representation, communication, and storage.
Prior to the JSON specification, most client-server communications were being deliv‐ ered in much more verbose XML snippets. JavaScript developers often work with JSON web services and frequently define internal data using JSON syntax.
Anatomy of a Typical Modern JavaScript App | 5
Take this example message, describing a collection of books:
[ { "title" : "JavaScript: The Good Parts", "author" : "Douglas Crockford", "ISBN" : "0596517742" }, { "title" : "JavaScript Patterns", "author" : "Stoyan Stefanov", "ISBN" : "0596806752" } ]
As you can see, this format is nearly identical to JavaScript’s object-literal syntax, with a couple important differences:
Prior to the advent of Extensible Markup Language (XML) and JSON data stores, nearly all web services were backed by RDBMS. An RDBMS stores discrete data points in tables and groups data output using table lookups in response to SQL queries.
NoSQL data stores, in contrast, store entire records in documents or document snippets without resorting to table-based structured storage. Document-oriented data stores commonly store data in XML format, while object-oriented data stores commonly em‐ ploy the JSON format. The latter are particularly well suited to web application devel‐ opment, because JSON is the format you use to communicate natively in JavaScript.
Examples of popular JSON-based NoSQL data stores include MongoDB and CouchDB. Despite the recent popularity of NoSQL, it is still common to find modern JavaScript applications backed by MySQL and similar RDBMSs.
Representational State Transfer (REST) is a client-server communication architecture that creates a separation of concerns between data resources and user interfaces (or other data resource consumers, such as data analysis tools and aggregators). Services that implement REST are referred to as RESTful. The server manages data resources (such as user records). It does not implement the user interface (look and feel). Clients
6 | Chapter 1: The JavaScript Revolution