jQuery.proxy() usage

When you want a function that has the this value bound to a specific object. For example, in callbacks such as event handlers, AJAX callbacks, timeouts, intervals, custom objects, etc.

This is just a manufactured example of a situation where it might be useful. Assuming there is a Person object which has a property name. It is also linked to a text input element, and whenever the input value changes, the name in this person object gets updated too.

function Person(el) {
    this.name="";

    $(el).change(function(event) {
        // Want to update this.name of the Person object,
        // but can't because this here refers to the element
        // that triggered the change event.
    });
}

One solution that we often use is to store the this context in a variable and use that inside the callback function such as:

function Person(el) {
    this.name="";

    var self = this; // store reference to this

    $(el).change(function(event) {
        self.name = this.value; // captures self in a closure
    });
}

Alternatively, we could have used jQuery.proxy here so the reference to this refers to the object of Person instead of the element that triggered the event.

function Person(el) {
    this.name="";

    $(el).change(jQuery.proxy(function(event) {
        this.name = event.target.value;
    }, this));
}

Note that this feature has been standardized into ECMAScript 5 which now includes the bind method borrowed from and is already available on some browsers.

function Person(el) {
    this.name="";

    $(el).change(function(event) {
        this.name = event.target.value;
    }.bind(this)); // we're binding the function to the object of person
}

Leave a Comment