gpt4 book ai didi

javascript - jQuery.proxy() 用法

转载 作者:IT王子 更新时间:2023-10-29 02:51:06 30 4
gpt4 key购买 nike

我正在阅读关于 jQuery.proxy() 的 API .它看起来很有希望,但我想知道在什么情况下最好使用它。谁能赐教一下?

最佳答案

当您想要一个具有绑定(bind)到特定对象的 this 值的函数时。例如,在事件处理程序、AJAX 回调、超时、间隔、自定义对象等回调中。

这只是一个可能有用的情况的制造示例。假设有一个具有属性名称的 Person 对象。它还链接到文本输入元素,每当输入值发生变化时,此人对象中的名称也会更新。

function Person(el) {
this.name = '';

$(el).change(function(event) {
// Want to update this.name of the Person object,
// but can't because this here refers to the element
// that triggered the change event.
});
}

我们经常使用的一种解决方案是将 this 上下文存储在一个变量中,然后在回调函数中使用它,例如:

function Person(el) {
this.name = '';

var self = this; // store reference to this

$(el).change(function(event) {
self.name = this.value; // captures self in a closure
});
}

或者,我们可以在此处使用 jQuery.proxy,因此对 this 的引用是指 Person 的对象,而不是触发事件的元素。

function Person(el) {
this.name = '';

$(el).change(jQuery.proxy(function(event) {
this.name = event.target.value;
}, this));
}

请注意,此功能已标准化为 ECMAScript 5,现在包括 bind方法借自 并且已经在某些浏览器上可用。

function Person(el) {
this.name = '';

$(el).change(function(event) {
this.name = event.target.value;
}.bind(this)); // we're binding the function to the object of person
}

关于javascript - jQuery.proxy() 用法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3349380/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com