理解jQuery中的$ .proxy() [英] Understanding $.proxy() in jQuery
问题描述
从 docs 我了解 .proxy()
会改变作为参数传递的函数的范围。请问有人能更好地向我解释一下吗?我们为什么要这样做?
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?
推荐答案
它最终做的是确保这个<的值函数中的/ code>将是您想要的值。
What it ultimately does is it ensures that the value of this
in a function will be the value you desire.
一个常见的例子是 setTimeout
发生在点击
处理程序中。
A common example is in a setTimeout
that takes place inside a click
handler.
取此:
$('#myElement').click(function() {
// In this function, "this" is our DOM element.
$(this).addClass('aNewClass');
});
意图很简单。单击 myElement
时,它应该获得类 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.
但是如果我们想要在添加之前的短暂延迟怎么办?类?我们可能会使用 setTimeout
来完成它,但问题是我们为 setTimeout
提供的任何函数, 该函数内的
将是 window
而不是我们的元素。
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);
});
那么我们可以做的就是调用 $。proxy()
,将函数和我们想要赋值的值发送给 this
,它将返回一个保留该值的函数。
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
});
所以我们给了 $。proxy()
函数和我们想要的这个
的值,它返回了一个函数,它将确保这个
被正确设置。
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.
它是如何做到的?它只返回一个匿名函数,使用 .apply()
方法调用我们的函数,它允许它显式设置<$ c $的值c> this 。
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)
}
因此,这个匿名函数被赋予 setTimeout
,它所做的就是执行我们的原始函数具有正确的此
上下文。
So this anonymous function is given to setTimeout
, and all it does is execute our original function with the proper this
context.
这篇关于理解jQuery中的$ .proxy()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!