Javascript proxy()用法
我在看api关于。这看起来很有希望,但我想知道在什么情况下这是最好的使用。有人能告诉我吗?例如,如果您想创建回调。而不是:Javascript proxy()用法,javascript,jquery,prototypejs,Javascript,Jquery,Prototypejs,我在看api关于。这看起来很有希望,但我想知道在什么情况下这是最好的使用。有人能告诉我吗?例如,如果您想创建回调。而不是: var that = this; $('button').click(function() { that.someMethod(); }); 你可以做: $('button').click($.proxy(this.someMethod, this)); 或者,如果您创建了一个接受回调的插件,并且您必须为回调设置特定的上下文。这只是为闭包设置上下文的一种简写方
var that = this;
$('button').click(function() {
that.someMethod();
});
你可以做:
$('button').click($.proxy(this.someMethod, this));
或者,如果您创建了一个接受回调的插件,并且您必须为回调设置特定的上下文。这只是为闭包设置上下文的一种简写方法,例如:
$(".myClass").click(function() {
setTimeout(function() {
alert(this); //window
}, 1000);
});
但是,我们通常希望此
与我们使用的方法保持相同,该方法使用$.proxy()
,如下所示:
$("button").click(function() {
setTimeout($.proxy(function() {
alert(this); //button
}, this), 1000);
});
它通常用于延迟的调用,或者任何您不想使用直接方法声明闭包的地方。将上下文指向对象的string方法……我还没有在日常代码中找到实际用途,但我确信有一些应用程序,只是取决于对象/事件结构是什么。当您需要一个将
此
值绑定到特定对象的函数时。例如,在事件处理程序、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
,因此对this
的引用是指Person的对象,而不是触发事件的元素
function Person(el) {
this.name = '';
$(el).change(jQuery.proxy(function(event) {
this.name = event.target.value;
}, this));
}
请注意,此功能已被标准化为ECMAScript 5,它现在包括从中借用的方法,并且已经在某些浏览器上可用
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
}
+1为了说明这一点,ECMAscript.Is使用常规闭包或使用$.proxy?@AnsonMacKeracher更好(更快、更高效),最好不要使用闭包,而是使用代理静态函数。这些答案并没有表明代理可以与静态函数一起使用,而作为
self=this
hack只能在您在线创建函数的情况下使用,只是为了更进一步,在ECMAScript 6(ES6)中,箭头函数是前进的方向()`function Person(el){this.name='';$(el).change((event)=>{this.name=event.target.value;});}`另请参阅,以获得详细解释