它最终要做的是确保this
函数中将是您想要的值。
一个常见的例子是setTimeout
发生在一个click
处理程序。
拿着它:
$('#myElement').click(function() {
// In this function, "this" is our DOM element.
$(this).addClass('aNewClass');
});
意图很简单。什么时候myElement
被点击,它应该得到类aNewClass
。处理程序内部this
代表被点击的元素。
但是如果我们想在添加类之前有短暂的延迟怎么办?我们可能会使用一个setTimeout
来完成它,但问题是无论我们赋予什么功能setTimeout
, 的价值this
该函数内部将是window
而不是我们的元素。
$('#myElement').click(function() {
setTimeout(function() {
// Problem! In this function "this" is not our element!
$(this).addClass('aNewClass');
}, 1000);
});
所以我们可以做的是调用$.proxy()
,向其发送我们想要分配的函数和值this
,它将返回一个保留该值的函数。
$('#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()
函数和我们想要的值this
,它返回一个函数,该函数将确保this
已正确设置。
它是如何做到的?它只是返回一个匿名函数calls我们的函数使用.apply()
方法,它可以显式设置this
.
返回的函数的简化外观可能如下所示:
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
,它所做的就是用正确的方式执行我们的原始函数this
语境。