SyntaxStudy
Sign Up
jQuery jQuery $.proxy() and Context Binding
jQuery Intermediate 5 min read

jQuery $.proxy() and Context Binding

In JavaScript, the value of this inside a callback depends on how the function is called, not where it is defined. This often breaks event handlers that reference object properties or methods. $.proxy(function, context) binds a function to a specific this value, returning a new function where this always refers to context.

Why This Matters

When jQuery fires an event handler, it sets this to the DOM element that triggered the event. If your handler is a method of an object that needs to read this.someProperty, you need to bind the correct context — otherwise this will be the DOM element, not your object.

Modern Alternative

ES6's Function.prototype.bind() and arrow functions (() => {}) solve the same problem natively. In modern jQuery projects, prefer arrow functions for new code, but understand $.proxy() when reading legacy codebases.

  • $.proxy(fn, context) — returns bound function
  • $.proxy(obj, methodName) — bind a named method of an object
  • Equivalent to fn.bind(context) in ES5+
  • Arrow functions in ES6 lexically bind this
Example
// Problem: "this" is the DOM element inside the handler
var app = {
    message: 'Hello from app!',
    init: function () {
        // Without proxy — "this" inside handler = button DOM element
        // $('#btn').on('click', this.greet); // broken!

        // With $.proxy — "this" inside greet = app object
        $('#btn').on('click', $.proxy(this.greet, this));
    },
    greet: function () {
        alert(this.message); // "Hello from app!"
    }
};
app.init();

// Proxy by method name
var obj = {
    val: 42,
    show: function () { console.log(this.val); }
};
$('#show-btn').on('click', $.proxy(obj, 'show'));

// Modern ES6 equivalent (preferred in new code)
$('#btn2').on('click', () => app.greet());
Pro Tip

In new code prefer ES6 arrow functions for context binding — use $.proxy() only when working with legacy codebases.