jQuery.proxy() 用法

2023-12-02

我正在阅读有关的 apijQuery.proxy()。它看起来很有希望,但我想知道在什么情况下最好使用它。谁能启发我吗?


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

这只是一个可能有用的情况的制造示例。假设有一个Person具有属性名称的对象。它还链接到文本输入元素,每当输入值发生变化时,此 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方法借用自原型js并且已经在某些浏览器上可用。

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
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

jQuery.proxy() 用法 的相关文章

随机推荐