You are previewing JavaScript Patterns.

JavaScript Patterns

Cover of JavaScript Patterns by Stoyan Stefanov Published by O'Reilly Media, Inc.
  1. JavaScript Patterns
  2. Dedication
  3. 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
  4. 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
  5. 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
  6. 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
  7. 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
  8. 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
  9. 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
  10. 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
      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
  11. 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
      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
      4. Lazy-Loading
      5. Loading on Demand
      6. Preloading JavaScript
    8. Summary
  12. Index
  13. About the Author
  14. Colophon
  15. Copyright
O'Reilly logo

Chapter 7. Design Patterns

The design patterns from the Gang of Four book offer solutions to common problems related to the object-oriented software design. They have been around for quite a while and have been proven useful in many situations. That’s why it’s good to familiarize yourself with them and to talk about them.

Although these design patterns are language-independent and implementation-agnostic, they have been studied for many years, mainly from the perspective of strongly typed static-class languages, such as C++ and Java.

JavaScript, being an untyped dynamic prototype-based language, sometimes makes it surprisingly easy, even trivial, to implement some of these patterns.

Let’s start with the first example of how things are different in JavaScript compared to a static class-based language—the singleton pattern.

Singleton

The idea of the singleton pattern is to have only one instance of a specific class. This means that the second time you use the same class to create a new object, you should get the same object that was created the first time.

And how does this apply to JavaScript? In JavaScript there are no classes, just objects. When you create a new object, there’s actually no other object like it, and the new object is already a singleton. Creating a simple object using the object literal is also an example of a singleton:

var obj = {
    myprop: 'my value'
};

In JavaScript, objects are never equal unless they are the same object, so even if you create an identical object with ...

The best content for your career. Discover unlimited learning on demand for around $1/day.