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?
From docs I understand that .proxy() would change the scope of the function passed
Share
What it ultimately does is it ensures that the value of
thisin a function will be the value you desire.A common example is in a
setTimeoutthat takes place inside aclickhandler.Take this:
The intention is simple enough. When
myElementis clicked, it should get the classaNewClass. Inside the handlerthisrepresents the element that was clicked.But what if we wanted a short delay before adding the class? We might use a
setTimeoutto accomplish it, but the trouble is that whatever function we give tosetTimeout, the value ofthisinside that function will bewindowinstead of our element.So what we can do instead, is to call
$.proxy(), sending it the function and the value we want to assign tothis, and it will return a function that will retain that value.So after we gave
$.proxy()the function, and the value we want forthis, it returned a function that will ensure thatthisis 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 ofthis.A simplified look at the function that is returned may look like:
So this anonymous function is given to
setTimeout, and all it does is execute our original function with the properthiscontext.