www.it-ebooks.info www.it-ebooks.info JavaScript Patterns www.it-ebooks.info www.it-ebooks.info JavaScript Patterns Stoyan Stefanov Beijing • Cambridge • Farnham • Köln • Sebastopol • Tokyo www.it-ebooks.info JavaScript Patterns by Stoyan Stefanov Copyright © 2010 Yahoo!, Inc 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 corporate@oreilly.com. Editor: Mary Treseler Production Editor: Teresa Elsey Copyeditor: ContentWorks, Inc. Proofreader: Teresa Elsey Indexer: Potomac Indexing, LLC Cover Designer: Karen Montgomery Interior Designer: David Futato Illustrator: Robert Romano Printing History: September 2010: First Edition. Nutshell Handbook, the Nutshell Handbook logo, and the O’Reilly logo are registered trademarks of O’Reilly Media, Inc. JavaScript Patterns, the image of a European partridge, 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 author assume no responsibility for errors or omissions, or for damages resulting from the use of the information con- tained herein. ISBN: 978-0-596-80675-0 [SB] 1284038177 www.it-ebooks.info To my girls: Eva, Zlatina, and Nathalie www.it-ebooks.info www.it-ebooks.info Table of Contents Preface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xiii 1. Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1 Patterns 1 JavaScript: Concepts 3 Object-Oriented 3 No Classes 4 Prototypes 4 Environment 5 ECMAScript 5 5 JSLint 6 The Console 6 2. Essentials . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9 Writing Maintainable Code 9 Minimizing Globals 10 The Problem with Globals 11 Side Effects When Forgetting var 12 Access to the Global Object 13 Single var Pattern 13 Hoisting: A Problem with Scattered vars 14 for Loops 15 for-in Loops 17 (Not) Augmenting Built-in Prototypes 19 switch Pattern 20 Avoiding Implied Typecasting 21 Avoiding eval() 21 Number Conversions with parseInt() 23 Coding Conventions 23 Indentation 24 Curly Braces 24 vii www.it-ebooks.info Opening Brace Location 25 White Space 26 Naming Conventions 28 Capitalizing Constructors 28 Separating Words 28 Other Naming Patterns 29 Writing Comments 30 Writing API Docs 30 YUIDoc Example 31 Writing to Be Read 34 Peer Reviews 35 Minify…In Production 36 Run JSLint 37 Summary 37 3. Literals and Constructors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39 Object Literal 39 The Object Literal Syntax 40 Objects from a Constructor 41 Object Constructor Catch 41 Custom Constructor Functions 42 Constructor’s Return Values 43 Patterns for Enforcing new 44 Naming Convention 45 Using that 45 Self-Invoking Constructor 46 Array Literal 46 Array Literal Syntax 47 Array Constructor Curiousness 47 Check for Array-ness 48 JSON 49 Working with JSON 49 Regular Expression Literal 50 Regular Expression Literal Syntax 51 Primitive Wrappers 52 Error Objects 53 Summary 54 4. Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 57 Background 57 Disambiguation of Terminology 58 Declarations Versus Expressions: Names and Hoisting 59 Function’s name Property 60 viii | Table of Contents www.it-ebooks.info [...]... types of patterns: • Design patterns • Coding patterns • Antipatterns Design patterns are those initially defined by the “Gang of Four” book (named so after its four authors), originally published in distant 1994 under the title Design Patterns: Elements of Reusable Object-Oriented Software Examples of design patterns are singleton, factory, decorator, observer, and so on The thing about design patterns. .. the class-based inheritance In JavaScript there might be simpler alternatives This book discusses JavaScript implementations of several design patterns in Chapter 7 The coding patterns are much more interesting; they are JavaScript- specific patterns and good practices related to the unique features of the language, such as the various uses of functions JavaScript coding patterns are the main topic of... some suggested titles: • • • • • • Object-Oriented JavaScript by yours truly (Packt Publishing) JavaScript: The Definitive Guide by David Flanagan (O’Reilly) JavaScript: The Good Parts by Douglas Crockford (O’Reilly) Pro JavaScript Design Patterns by Ross Hermes and Dustin Diaz (Apress) High Performance JavaScript by Nicholas Zakas (O’Reilly) Professional JavaScript for Web Developers by Nicholas Zakas... 1: Introduction www.it-ebooks.info Environment JavaScript programs need an environment to run The natural habitat for a JavaScript program is the browser, but that’s not the only environment The patterns in the book are mostly related to the core JavaScript (ECMAScript) so they are environmentagnostic Exceptions are: • Chapter 8, which specifically deals with browser patterns • Some other examples that illustrate... on The thing about design patterns in relation to JavaScript is that, although language-independent, the design patterns were mostly studied from the perspective of strongly typed languages, such as C++ and Java Sometimes it doesn’t necessarily make sense to apply them verbatim in a loosely typed dynamic language such as JavaScript Sometimes these patterns are workarounds that deal with the strongly... Contents | xi www.it-ebooks.info Loading on Demand Preloading JavaScript Summary 203 205 206 Index 209 xii | Table of Contents www.it-ebooks.info Preface Patterns are solutions to common problems One step further, patterns are templates for solving categories of problems Patterns help you split a problem into Lego-like blocks and focus... (http://nczonline.net, @slicknet) Remy Sharp (http://remysharp.com, @rem) Iliyan Peychev Credits Some of the patterns in the book were identified by the author, based on experience and on studies of popular JavaScript libraries such as jQuery and YUI But most of the patterns are identified and described by the JavaScript community; therefore, this book is a result of the collective work of many developers To... as object creation or hoisting) may look too basic to be in this book, but they are discussed from a patterns perspective and, in my opinion, are critical to harnessing the power of the language If you’re looking for best practices and powerful patterns to help you write better, maintainable, robust JavaScript code, this book is for you Conventions Used in This Book The following typographical conventions... anonymous functions, which JavaScript developers have been enjoying and taking for granted for a while JavaScript is dynamic enough that you can make it look and feel like another language you’re already comfortable with But the better approach is to embrace its differences and study its specific patterns Patterns A pattern in the broader sense of the word is a “theme of recurring events or objects… it... occasional antipattern in the book Antipatterns have a bit of negative or even insulting sound to their name, but that needn’t be the case An antipattern is not the same as a bug or a coding error; it’s just a common approach that causes more problems than it solves Antipatterns are clearly marked with a comment in the code 2 | Chapter 1: Introduction www.it-ebooks.info JavaScript: Concepts Let’s quickly . it.” This book discusses the following types of patterns: • Design patterns • Coding patterns • Antipatterns Design patterns are those initially defined by the. discusses JavaScript im- plementations of several design patterns in Chapter 7. The coding patterns are much more interesting; they are JavaScript- specific patterns and