Rei*_*gel 68 javascript jquery
我在读api jQuery.proxy().它看起来很有希望,但我想知道在什么情况下这是最好用的.任何人都可以开导我吗?
Anu*_*rag 135
当您需要具有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.
});
}
Run Code Online (Sandbox Code Playgroud)
我们经常使用的一个解决方案是将此上下文存储在变量中,并在回调函数中使用它,例如:
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
});
}
Run Code Online (Sandbox Code Playgroud)
或者,我们可以在jQuery.proxy这里使用,所以引用引用thisPerson的对象而不是触发事件的元素.
function Person(el) {
this.name = '';
$(el).change(jQuery.proxy(function(event) {
this.name = event.target.value;
}, this));
}
Run Code Online (Sandbox Code Playgroud)
请注意,此功能已标准化为ECMAScript 5,现在包含bind从prototypejs借用的方法,并且已在某些浏览器上提供.
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
}
Run Code Online (Sandbox Code Playgroud)
Nic*_*ver 17
它只是为闭包设置上下文的简写方法,例如:
$(".myClass").click(function() {
setTimeout(function() {
alert(this); //window
}, 1000);
});
Run Code Online (Sandbox Code Playgroud)
但是,我们通常希望this保持与我们所$.proxy()使用的方法相同的方式,如下所示:
$("button").click(function() {
setTimeout($.proxy(function() {
alert(this); //button
}, this), 1000);
});?
Run Code Online (Sandbox Code Playgroud)
它通常用于延迟调用,或任何你不想做一个声明闭包的简化方法的地方.将上下文指向对象的字符串方法......好吧我还没有在日常代码中遇到过实际用法,但我确信有应用程序,只是取决于你的对象/事件结构.
Fel*_*ing 14
例如,如果要创建回调.代替:
var that = this;
$('button').click(function() {
that.someMethod();
});
Run Code Online (Sandbox Code Playgroud)
你可以做:
$('button').click($.proxy(this.someMethod, this));
Run Code Online (Sandbox Code Playgroud)
或者,如果您创建一个接受回调的插件,则必须为回调设置特定的上下文.
| 归档时间: |
|
| 查看次数: |
35244 次 |
| 最近记录: |