当你想要一个具有以下功能的函数时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
}