Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the difference between $.proxy and the native js 'call' / 'apply'?

I believe they both allow you to control the value of 'this', but beyond that, I'm a little unclear and Google/SO isn't helping much so far. Any clarification appreciated. I did find this, but I'm skeptical that it tells the whole story:

"When I first learned about jQuery's proxy() method, I thought it was a little silly; after all, Javascript already has call() and apply() methods for changing execution context. But, once you realize that jQuery's proxy() method allows you to easily bind() and unbind() event handlers regardless of context, it becomes obvious just how powerful this method is.

like image 718
GregT Avatar asked Feb 20 '13 23:02

GregT


1 Answers

call/apply are a single-shot invocation. $.proxy creates a new function permanently bound to something:

fn.call(foo);  //call once

var otherFn = $.proxy(fn, foo);  // you can call it again later

var otherOtherFn = fn.bind(foo);  // ES5 standard way

As a simplification (very simplified), $.proxy is creating a new function that calls call:

$.proxy = function(fn, newThis) {
    return function() {
        fn.call(newThis);
    }
}

It is analogous to ES5's Function.prototype.bind

like image 169
Dennis Avatar answered Oct 27 '22 21:10

Dennis