168

From docs I understand that .proxy() would change the scope of the function passed as an argument. Could someone please explain me this better? Why should we do this?

Sebastian Simon
  • 14,320
  • 6
  • 42
  • 61
Aditya Shukla
  • 12,229
  • 11
  • 34
  • 36
  • 1
    According to the documentation, "This method is most useful for attaching event handlers to an element where the context is pointing back to a different object. Additionally, jQuery makes sure that even if you bind the function returned from jQuery.proxy() it will still unbind the correct function, if passed the original". Is there anything particular about that phrasing you find lacking? – bzlm Feb 13 '11 at 19:36
  • 1
    This is unclear here Additionally, jQuery makes sure that even if you bind the function returned from jQuery.proxy() it will still unbind the correct function, if passed the original".What's meant by original? – Aditya Shukla Feb 13 '11 at 19:46
  • The original is that for which a proxy was created. But since you don't fully grasp this stuff, are you sure you need to use it? – bzlm Feb 13 '11 at 19:55
  • 1
    @bzlm , I was reading jquery documentation when i came up at this method. – Aditya Shukla Feb 14 '11 at 00:48
  • 1
    Here's a great video tutorial by nettuts showing how $.proxy works. [http://net.tutsplus.com/tutorials/javascript-ajax/quick-tip-learning-jquery-1-4s-proxy/](http://net.tutsplus.com/tutorials/javascript-ajax/quick-tip-learning-jquery-1-4s-proxy/) – Hussein Feb 13 '11 at 20:13
  • for more advanced, i would recommend this question too: [javascript - What is the difference between $.proxy() and bind()? - Stack Overflow](https://stackoverflow.com/questions/12501231/what-is-the-difference-between-proxy-and-bind) – aaron Aug 15 '19 at 14:22
  • [This video](https://frontendmasters.com/courses/javascript-jquery-dom/exercise-11-implementing-proxy/) in FrontendMasters helped me a lot to release it since the teacher explains what is happening in the memory with the references to the functions/objects in plain js – Nasia Makrygianni Oct 29 '19 at 15:04

4 Answers4

382

What it ultimately does is it ensures that the value of this in a function will be the value you desire.

A common example is in a setTimeout that takes place inside a click handler.

Take this:

$('#myElement').click(function() {
        // In this function, "this" is our DOM element.
    $(this).addClass('aNewClass');
});

The intention is simple enough. When myElement is clicked, it should get the class aNewClass. Inside the handler this represents the element that was clicked.

But what if we wanted a short delay before adding the class? We might use a setTimeout to accomplish it, but the trouble is that whatever function we give to setTimeout, the value of this inside that function will be window instead of our element.

$('#myElement').click(function() {
    setTimeout(function() {
          // Problem! In this function "this" is not our element!
        $(this).addClass('aNewClass');
    }, 1000);
});

So what we can do instead, is to call $.proxy(), sending it the function and the value we want to assign to this, and it will return a function that will retain that value.

$('#myElement').click(function() {
   // ------------------v--------give $.proxy our function,
    setTimeout($.proxy(function() {
        $(this).addClass('aNewClass');  // Now "this" is again our element
    }, this), 1000);
   // ---^--------------and tell it that we want our DOM element to be the
   //                      value of "this" in the function
});

So after we gave $.proxy() the function, and the value we want for this, it returned a function that will ensure that this is properly set.

How does it do it? It just returns an anonymous function that calls our function using the .apply() method, which lets it explicitly set the value of this.

A simplified look at the function that is returned may look like:

function() {
    // v--------func is the function we gave to $.proxy
    func.apply( ctx );
    // ----------^------ ctx is the value we wanted for "this" (our DOM element)
}

So this anonymous function is given to setTimeout, and all it does is execute our original function with the proper this context.

user113716
  • 299,514
  • 60
  • 431
  • 433
  • What's the value of using `$.proxy(function () {...}, this)` rather than `(function() {...}).call(this)`? Is there a difference? – Justin Morgan Jul 19 '12 at 15:45
  • 11
    @JustinMorgan: with `.call` you are calling the function immediately. With `$.proxy`, it is like `Function.prototype.bind` where it returns a new function. That new function has the `this` value permanently bound, so that when it is passed to `setTimeout`, and `setTimeout` calls the function later, it will still have the correct `this` value. – gray state is coming Aug 18 '12 at 02:25
  • 2
    What's the advantage, if any, of this technique over something like this? $('#myElement').click(function() { var el = $(this); setTimeout(function() { el.addClass('aNewClass'); }, 1000); }); – Greg Nov 14 '12 at 22:56
  • You don't need to use jQuery for this. You can achieve it by using plain JS, too: $('#myElement').click(function() { setTimeout((function (this) { return function () { this.className = this.className + " aNewClass"; } })(this)), 1000); }); – keinabel Feb 21 '13 at 15:23
  • 1
    You do not have to use $.proxy method for this example .Instead you can simply re -write it like this $('#myElement').click(function() { var that = this; setTimeout(function() { // new context through a variable declared in scope of handler method $(that).addClass('aNewClass'); }, 1000); }); – paul Mar 07 '13 at 20:01
  • hey can you just clear my doubt related to `$.proxy()` I posted [here](http://stackoverflow.com/questions/17946312/why-the-handler-attached-using-proxy-is-not-getting-detached-after-first-c) – Mahesha999 Jul 30 '13 at 13:05
  • 5
    An anonymous user with 112k rep, scary-good JavaScript/jQuery knowledge, and hasn't been seen since October 2011... John Resig perhaps? – cantera Sep 04 '13 at 14:06
  • I like non-passive aggressive answers like this one :) Now I get it! – Arnaldo Capo Dec 30 '13 at 17:01
  • @cantera you mean a dual identity apart from [John Resig](http://stackoverflow.com/users/6524/john-resig)? :) – msanjay Jul 16 '14 at 13:10
  • This what I call an explanation! – ShAkKiR May 23 '18 at 06:16
50

Without going into greater detail (which would be necessary because this is about Context in ECMAScript, the this context variable etc.)

There are three different types of "Contexts" in ECMA-/Javascript:

  • The global context
  • Function context
  • eval context

Every code is executed in its execution context. There is one global context and there can be many instances of function (and eval) contexts. Now the interesting part:

Every call of a function enters the function execution context. An execution context of a function looks like:

The Activation Object
Scope Chain
this value

So the this value is a special object which is related with the execution context. There are two functions in ECMA-/Javascript which may change the this value in a function execution context:

.call()
.apply()

If we have a function foobar() we can change the this value by calling:

foobar.call({test: 5});

Now we could access in foobar the object we passed in:

function foobar() { 
    this.test // === 5
}

This is exactly what jQuery.proxy() does. It takes a function and context (which is nothing else than an object) and links the function by invoking .call() or .apply() and returns that new function.

prateekj_ahead
  • 147
  • 1
  • 1
  • 11
jAndy
  • 212,463
  • 51
  • 293
  • 348
4

I have written this function:

function my_proxy (func,obj)
{
    if (typeof(func)!="function")
        return;

    // If obj is empty or another set another object 
    if (!obj) obj=this;

    return function () { return func.apply(obj,arguments); }
}
vidriduch
  • 4,463
  • 6
  • 40
  • 56
sgv_test
  • 1,165
  • 8
  • 6
1

The same goal can be achieved using a "Immediately-Invoked Function Expression, short: IIFE" self executing function:

    $('#myElement').click(function() {  
      (function(el){
         setTimeout(function() {
              // Problem! In this function "this" is not our element!
            el.addClass('colorme');
        }, 1000);
      })($(this)); // self executing function   
    });
.colorme{
  color:red;
  font-size:20px;
}
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>
</head>
<body>
<script src="https://code.jquery.com/jquery-3.1.0.js"></script>

  <div id="myElement">Click me</div>
</body>
</html>
Legends
  • 16,460
  • 9
  • 75
  • 108
  • 2
    That's usually called an "Immediately-Invoked Function Expression" (IIFE) rather than a "self executing function", see https://en.wikipedia.org/wiki/Immediately-invoked_function_expression. – Chris Seed Jun 28 '17 at 14:35