在 jQuery 中了解 $.proxy()
从文档中,我知道这将改变作为参数传递的函数的范围。有人可以更好地解释我吗?我们为什么要这样做?.proxy()
它最终的作用是确保函数中的值将是您想要的值。this
一个常见的例子是在处理程序内部发生的。setTimeout
click
拿着这个:
$('#myElement').click(function() {
// In this function, "this" is our DOM element.
$(this).addClass('aNewClass');
});
意图很简单。单击 时,它应获取类 。处理程序内部表示单击的元素。myElement
aNewClass
this
但是,如果我们想要在添加类之前有一个短暂的延迟呢?我们可能会使用 a 来完成它,但问题是,无论我们给 什么函数,该函数内部的值都将不是我们的元素。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
它是如何做到的?它只是返回一个匿名函数,该函数使用该方法调用我们的函数,该方法允许它显式设置的值。.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
没有更详细地讨论(这是必要的,因为这是关于 ECMAScript 中的上下文,this 上下文变量等)。
ECMA-/Javascript 中有三种不同类型的“上下文”:
每个代码都在其执行上下文中执行。有一个全局上下文,并且可以有许多函数(和评估)上下文的实例。现在有趣的部分:
函数的每次调用都会进入函数执行上下文。函数的执行上下文如下所示:
激活对象
作用域链接
此值
因此,this 值是与执行上下文相关的特殊对象。ECMA-/Javascript 中有两个函数可能会更改函数执行上下文中的 this 值:
.call()
.apply()
如果我们有一个函数,我们可以通过调用来更改此值:foobar()
foobar.call({test: 5});
现在我们可以访问我们传入的对象:foobar
function foobar() {
this.test // === 5
}
这正是它的作用。它采用 and(它只不过是一个对象),并通过调用 或 链接函数并返回该新函数。jQuery.proxy()
function
context
.call()
.apply()