Back
Syntax
Study
Editor
Mode:
HTML
CSS
JavaScript
PHP
Reset
Run »
HTML / CSS / JS
// 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());
Result
Open