Skip to Content
Learning JavaScript Design Patterns
book

Learning JavaScript Design Patterns

by Addy Osmani
July 2012
Intermediate to advanced content levelIntermediate to advanced
254 pages
6h 16m
English
O'Reilly Media, Inc.
Content preview from Learning JavaScript Design Patterns

Decorators with jQuery

As with other patterns we’ve covered, there are also examples of the Decorator pattern that can be implemented with jQuery. jQuery.extend() allows us to extend (or merge) two or more objects (and their properties) together into a single object either at run-time or dynamically at a later point.

In this scenario, a target object can be decorated with new functionality without necessarily breaking or overriding existing methods in the source/superclass object (although this can be done).

In the following example, we define three objects: defaults, options, and settings. The aim of the task is to decorate the defaults object with additional functionality found in optionssettings. We must first leave defaults in an untouched state where we don’t lose the ability to access the properties or functions found in it at a later point; then, gain the ability to use the decorated properties and functions found in options:

var decoratorApp = decoratorApp || {};

// define the objects we're going to use
decoratorApp = {

    defaults: {
        validate: false,
        limit: 5,
        name: "foo",
        welcome: function () {
            console.log( "welcome!" );
        }
    },

    options: {
        validate: true,
        name: "bar",
        helloWorld: function () {
            console.log( "hello world" );
        }
    },

    settings: {},

    printObj: function ( obj ) {
        var arr = [],
            next;
        $.each( obj, function ( key, val ) {
            next = key + ": ";
            next += $.isPlainObject(val) ? printObj( val ) : val;
            arr.push( next );
        } );

        return "{ " + arr.join(", ") + " }";
    }

};

// merge defaults ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Mastering JavaScript Design Patterns - Second Edition

Mastering JavaScript Design Patterns - Second Edition

Simon Timms
JavaScript Patterns

JavaScript Patterns

Stoyan Stefanov

Publisher Resources

ISBN: 9781449334840Errata Page