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

The Proxy Pattern

There are times when it is necessary for us to control the access and context behind an object, and this is where the Proxy pattern can be useful.

It can help us control when an expensive object should be instantiated, provide advanced ways to reference the object, or modify the object to function a particular way in specific contexts.

In jQuery core, a jQuery.proxy() method exists that accepts as input a function and returns a new one that will always have a specific context. This ensures that the value of this within a function is the value we expect.

An example of where this is useful is when we’re making use of timers within a click event handler. Imagine we have the following handler prior to adding any timers:

$( "button" ).on( "click", function () {
  // Within this function, "this" refers to the element that was clicked
  $( this ).addClass( "active" );
});

If we wished to add a hard delay before the active class was added, we could use setTimeout() to achieve this. Unfortunately there is a small problem with this solution: whatever function is passed to setTimeout() will have a different value for this within that function. It will instead refer to the window object, which is not what we desire.

$( "button" ).on( "click", function () {
  setTimeout(function () {
    // "this" doesn't refer to our element!
    // It refers to window
    $( this ).addClass( "active" );
  });
});

To work around this problem, we can use jQuery.proxy() to implement a type of proxy pattern. By calling ...

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