A JavaScript pattern and antipattern collection that covers function patterns, jQuery patterns, jQuery plugin patterns, design patterns, general patterns, literals and constructor patterns, object creation patterns, code reuse patterns, DOM and browser patterns (upcoming).
Patterns collected while developing 喜感网.General Patterns
- Function Declarations - creating anonymous functions and assigning them to a variable
- Conditionals - pattern and antipattern of using if else
- Access to the Global Object - access the global object without hard-coding the identifier window
- Single var Pattern - use one var statement and declare multiple variables
- Hoisting - var statements anywhere in a function act as if the variables were declared at the top of the function
- for loops - optimized for loops
- for-in loops - optimized for-in loops
- (Not) Augmenting Built-in Prototypes - only augment built-in prototypes when certain conditions are met
- switch Pattern - improve the readability and robustness of your switch statements
- Implied Typecasting - avoid implied typecasting
- Avoiding eval() - avoid using eval()
- Number Conversions with parseInt() - use the second radix parameter
- Minimizing Globals - create and access a global variable in a browser environment
- The Problem with Globals - various problems with globals
jQuery Patterns
- requery - avoid requery by using jQuery chaining
- append - use string concatenate and set innerHTML
- data - pattern and antipattern of using data
- context and find - use find over context
- detach - take element off the DOM while manipulating them
- event delegation - event delegation pattern and antipattern
- selector cache - using selector cache to avoid requery
- window scroll event - avoid attaching handlers to the window scroll event
Selector
- Left and Right - specific on the right, light on the left
- Decending from id - be more specific
- Universal Selector - use of universal selector
- Be Specific when Needed - be specific only when needed
Publish–subscribe
jQuery Plugin Patterns
- Basic - the most basic pattern
- Extend - enables you to define multiple functions at once and which sometimes make more sense semantically
- Lightweight - perfect as a generic template for beginners and above
- Namespaced pattern - to avoid collisions and improve code organization when working with components under another namespace
- Prototypal inheritance - prototypal inheritance with the DOM-to-Object bridge pattern
- Best options - globally/Per-call overridable options for greater option customization
- Custom events (Pseudo Pub/Sub) - for better application decoupling
- 'Highly configurable' mutable - define plugin’s logic using a constructor and an object literal defined on its prototype
- UI Widget factory - for building complex, stateful plugins based on object-oriented principles
- UI Widget factory "bridge" - the bridge serves as a middle layer between a JavaScript object that is created using $.widget and jQuery’s API
- UI Widget factory for jQuery mobile - demonstrating best practices for building mobile widgets
- UI Widget + RequireJS module - for wrapping jQueryUI widgets inside RequireJS compatible modules
- Universal Module Definition pattern - create AMD and CommonJS compatible plugin modules which are compatible with a number of different script loaders
Literals and Constructors Patterns
- Object literal - use the simpler and reliable object literal instead of new Object();
- Enforcing new - when you forget `new`, `this` inside the constructor will point to the global object
- Array literal - use array literal notation to avoid potential errors when creating dynamic arrays at runtime
- Working with JSON - use library from JSON.org, YUI, jQuery instead of eval for parsing
- Primitive wrappers - try to use the primitive without wrapper
- Regular expression literal - try to use the shorter literal notation
Function Patterns
API Patterns
- Callback patterns - when you pass function A to function B as a parameter, function A is a callback function
- Configuration objects - keep control of function arguments and makes it easily configurable
- Returning functions - one function returns another function or create another function on-demand
- Currying - used to create new functions dynamically by partially applying a set of arguments
- Partial application - the process of fixing a number of arguments to a function, producing another function of smaller arity
Initialization patterns
- Immediate functions - syntax that enables function execution as soon as it is defined
- Immediate object initialization - this pattern is mainly suitable for one-off tasks
- Init-time branching - branch code once during initlization initialization
Performance patterns
- Memoization - use function properties to avoid repeated computation
- Self-defining functions - self-overwrite with new bodies to do less work from the second invocation and after
Object Creation Patterns
- Namespace - namespaces help reduce the number of globals required and avoid naming collisions or excessive name prefixing
- Declaring Dependencies - it's good to declare the modules your code relies on at the top
- Private Properties and Methods - JavaScript doesn't have special syntax for private members, you can implement them using a closure
- Revelation Pattern - it is about having private methods, which you also expose as public methods
- Module Pattern - all the methods are kept private and you only expose those that you decide at the end
- Sandbox - it provides an environment for the modules to work without affecting other modules and their personal sandboxes
- Static Members - public and private static members
- Object Constants - an implementation of a contant object provides set, inDefined and get methods
- Chaining Pattern - it enables you to call methods on an object one after the other
- method() Method - adding convenient funcationality to a language
Code Reuse Patterns
Classical Patterns (patterns that should generally be avoided)
- The default pattern - create an object using the Parent() constructor and assign this object to the Child()'s prototype
- Rent a constructor - it borrows the parent constructor, passing the child object to be bound to this and also forwarding any arguments
- Rent and Set Prototype - restricts object creation for a class to only one instance
- Share the Prototype - restricts object creation for a class to only one instance
- A Temporary Constructor - first borrow the constructor and then also set the child's prototype to point to a new instance of the constructor
- Klass - generally a pattern that should be avoided unless one is more comfortable with class than prototype
Preferred Patterns
- Prototypal Inheritance - objects inherit from other objects
- Inheritance by Copying Properties - an object gets functionality from another object, simply by copying it
- Mix-ins - copy from any number of objects and mix them all into a new object
- Borrowing Methods - reuse one or two methods of an existing object without forming a parent-child relationship with that object
Design Patterns
Creational
- Builder - constructs complex objects by separating construction and representation
- Factory method - creates objects without specifying the exact class to create
- Singleton - restricts object creation for a class to only one instance
Structural
- Decorator - dynamically adds/overrides behaviour in an existing method of an object
- Facade - provides a simplified interface to a large body of code
- Proxy - provides a placeholder for another object to control access, reduce cost, and reduce complexity
Behavioral
- Chain of responsibility - delegates commands to a chain of processing objects
- Command - creates objects which encapsulate actions and parameters
- Iterator - implements a specialized language
- Mediator - allows loose coupling between classes by being the only class that has detailed knowledge of their methods
- Observer - is a publish/subscribe pattern which allows a number of observer objects to see an event
- Strategy - allows one of a family of algorithms to be selected on-the-fly at runtime
References
-
The Essentials of Writing High Quality JavaScript
http://net.tutsplus.com/tutorials/javascript-ajax/the-essentials-of-writing-high-quality-javascript/ -
JSPatterns
http://www.jspatterns.com/ -
jQuery Anti-Patterns for Performance & Compression
http://paulirish.com/2009/perf/ -
How DRY Affects JavaScript Performance
http://velocityconf.com/velocityeu/public/schedule/detail/21634 -
Object Oriented JavaScript
http://www.packtpub.com/object-oriented-javascript/book -
JavaScript Patterns
http://shop.oreilly.com/product/9780596806767.do -
JavaScript: The Good Parts
http://shop.oreilly.com/product/9780596517748.do -
Pro JavaScript Design Patterns
http://jsdesignpatterns.com/ -
Essential JavaScript Design Patterns For Beginners, Volume 1.
http://www.addyosmani.com/resources/essentialjsdesignpatterns/book/ -
Eloquent JavaScript
http://eloquentjavascript.net/