我正在阅读有关的api jQuery.proxy()。看起来很有希望,但我想知道这种最佳用法是什么情况。谁能启发我?
我正在阅读有关的api jQuery.proxy()。看起来很有希望,但我想知道这种最佳用法是什么情况。谁能启发我?
Answers:
当您需要一个具有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.
});
}
我们经常使用的一种解决方案是将该上下文存储在变量中,并在回调函数中使用它,例如:
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此处使用该引用,以便引用thisPerson的对象而不是触发事件的元素。
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
}
self = this只有在创建内联函数时才能使用hack
这只是为闭包设置上下文的简便方法,例如:
$(".myClass").click(function() {
setTimeout(function() {
alert(this); //window
}, 1000);
});
但是,通常我们希望this与以前$.proxy()使用的方法保持相同,就像这样:
$("button").click(function() {
setTimeout($.proxy(function() {
alert(this); //button
}, this), 1000);
});
它通常用于延迟调用,或者用于您不想做任何宣告关闭的方法的地方。将上下文指向对象的字符串方法...好吧,我还没有在日常代码中实际使用过这种方法,但是我敢肯定有应用程序,这取决于您的对象/事件结构是什么。