O'Reilly logo

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

JavaScript Patterns

Book Description

What's the best approach for developing an application with JavaScript? This book helps you answer that question with numerous JavaScript coding patterns and best practices. If you're an experienced developer looking to solve problems related to objects, functions, inheritance, and other language-specific categories, the abstractions and code templates in this guide are ideal—whether you're using JavaScript to write a client-side, server-side, or desktop application.

Written by JavaScript expert Stoyan Stefanov—Senior Yahoo! Technical and architect of YSlow 2.0, the web page performance optimization tool—JavaScript Patterns includes practical advice for implementing each pattern discussed, along with several hands-on examples. You'll also learn about anti-patterns: common programming approaches that cause more problems than they solve.

  • Explore useful habits for writing high-quality JavaScript code, such as avoiding globals, using single var declarations, and more
  • Learn why literal notation patterns are simpler alternatives to constructor functions
  • Discover different ways to define a function in JavaScript
  • Create objects that go beyond the basic patterns of using object literals and constructor functions
  • Learn the options available for code reuse and inheritance in JavaScript
  • Study sample JavaScript approaches to common design patterns such as Singleton, Factory, Decorator, and more
  • Examine patterns that apply specifically to the client-side browser environment

Table of Contents

  1. Dedication
  2. Preface
    1. Target Audience
    2. Conventions Used in This Book
    3. Using Code Examples
    4. Safari® Books Online
    5. How to Contact Us
    6. Acknowledgments
    7. Credits
    8. Reading
  3. 1. Introduction
    1. Patterns
    2. JavaScript: Concepts
      1. Object-Oriented
      2. No Classes
      3. Prototypes
      4. Environment
    3. ECMAScript 5
    4. JSLint
    5. The Console
  4. 2. Essentials
    1. Writing Maintainable Code
    2. Minimizing Globals
      1. The Problem with Globals
      2. Side Effects When Forgetting var
      3. Access to the Global Object
      4. Single var Pattern
      5. Hoisting: A Problem with Scattered vars
    3. for Loops
    4. for-in Loops
    5. (Not) Augmenting Built-in Prototypes
    6. switch Pattern
    7. Avoiding Implied Typecasting
    8. Avoiding eval()
    9. Number Conversions with parseInt()
    10. Coding Conventions
      1. Indentation
      2. Curly Braces
      3. Opening Brace Location
      4. White Space
    11. Naming Conventions
      1. Capitalizing Constructors
      2. Separating Words
      3. Other Naming Patterns
    12. Writing Comments
    13. Writing API Docs
      1. YUIDoc Example
    14. Writing to Be Read
    15. Peer Reviews
    16. Minify…In Production
    17. Run JSLint
    18. Summary
  5. 3. Literals and Constructors
    1. Object Literal
      1. The Object Literal Syntax
      2. Objects from a Constructor
      3. Object Constructor Catch
    2. Custom Constructor Functions
      1. Constructor’s Return Values
    3. Patterns for Enforcing new
      1. Naming Convention
      2. Using that
      3. Self-Invoking Constructor
    4. Array Literal
      1. Array Literal Syntax
      2. Array Constructor Curiousness
      3. Check for Array-ness
    5. JSON
      1. Working with JSON
    6. Regular Expression Literal
      1. Regular Expression Literal Syntax
    7. Primitive Wrappers
    8. Error Objects
    9. Summary
  6. 4. Functions
    1. Background
      1. Disambiguation of Terminology
      2. Declarations Versus Expressions: Names and Hoisting
      3. Function’s name Property
      4. Function Hoisting
    2. Callback Pattern
      1. A Callback Example
      2. Callbacks and Scope
      3. Asynchronous Event Listeners
      4. Timeouts
      5. Callbacks in Libraries
    3. Returning Functions
    4. Self-Defining Functions
    5. Immediate Functions
      1. Parameters of an Immediate Function
      2. Returned Values from Immediate Functions
      3. Benefits and Usage
    6. Immediate Object Initialization
    7. Init-Time Branching
    8. Function Properties—A Memoization Pattern
    9. Configuration Objects
    10. Curry
      1. Function Application
      2. Partial Application
      3. Currying
      4. When to Use Currying
    11. Summary
  7. 5. Object Creation Patterns
    1. Namespace Pattern
      1. General Purpose Namespace Function
    2. Declaring Dependencies
    3. Private Properties and Methods
      1. Private Members
      2. Privileged Methods
      3. Privacy Failures
      4. Object Literals and Privacy
      5. Prototypes and Privacy
      6. Revealing Private Functions As Public Methods
    4. Module Pattern
      1. Revealing Module Pattern
      2. Modules That Create Constructors
      3. Importing Globals into a Module
    5. Sandbox Pattern
      1. A Global Constructor
      2. Adding Modules
      3. Implementing the Constructor
    6. Static Members
      1. Public Static Members
      2. Private Static Members
    7. Object Constants
    8. Chaining Pattern
      1. Pros and Cons of the Chaining Pattern
    9. method() Method
    10. Summary
  8. 6. Code Reuse Patterns
    1. Classical Versus Modern Inheritance Patterns
    2. Expected Outcome When Using Classical Inheritance
    3. Classical Pattern #1—The Default Pattern
      1. Following the Prototype Chain
      2. Drawbacks When Using Pattern #1
    4. Classical Pattern #2—Rent-a-Constructor
      1. The Prototype Chain
      2. Multiple Inheritance by Borrowing Constructors
      3. Pros and Cons of the Borrowing Constructor Pattern
    5. Classical Pattern #3—Rent and Set Prototype
    6. Classical Pattern #4—Share the Prototype
    7. Classical Pattern #5—A Temporary Constructor
      1. Storing the Superclass
      2. Resetting the Constructor Pointer
    8. Klass
    9. Prototypal Inheritance
      1. Discussion
      2. Addition to ECMAScript 5
    10. Inheritance by Copying Properties
    11. Mix-ins
    12. Borrowing Methods
      1. Example: Borrow from Array
      2. Borrow and Bind
      3. Function.prototype.bind()
    13. Summary
  9. 7. Design Patterns
    1. Singleton
      1. Using new
      2. Instance in a Static Property
      3. Instance in a Closure
    2. Factory
      1. Built-in Object Factory
    3. Iterator
    4. Decorator
      1. Usage
      2. Implementation
      3. Implementation Using a List
    5. Strategy
      1. Data Validation Example
    6. Façade
    7. Proxy
      1. An Example
        1. A video expando
        2. Without a proxy
        3. HTML
        4. Event handlers
        5. videos object
        6. http object
        7. Enter the proxy
      2. Proxy As a Cache
    8. Mediator
      1. Mediator Example
    9. Observer
      1. Example #1: Magazine Subscriptions
      2. Example #2: The Keypress Game
    10. Summary
  10. 8. DOM and Browser Patterns
    1. Separation of Concerns
    2. DOM Scripting
      1. DOM Access
      2. DOM Manipulation
    3. Events
      1. Event Handling
      2. Event Delegation
    4. Long-Running Scripts
      1. setTimeout()
      2. Web Workers
    5. Remote Scripting
      1. XMLHttpRequest
      2. JSONP
        1. JSONP example: Tic-tac-toe
      3. Frames and Image Beacons
    6. Deploying JavaScript
      1. Combining Scripts
      2. Minifying and Compressing
      3. Expires Header
      4. Using a CDN
    7. Loading Strategies
      1. The Place of the <script> Element
      2. HTTP Chunking
      3. Dynamic <script> Element for Nonblocking Downloads
        1. Appending the <script> element
      4. Lazy-Loading
      5. Loading on Demand
      6. Preloading JavaScript
    8. Summary
  11. Index
  12. About the Author
  13. Colophon
  14. Copyright