在 jQuery 实用程序/ajax 方法中设置“this"的匿名函数范围 [英] Setting anonymous function scope of 'this' in jQuery utility / ajax methods
问题描述
如这篇博文所述,您可以设置this
在 Javascript 的匿名函数中.
As noted in this blog post you can set the scope of this
in an anonymous function in Javascript.
在 AJAX 请求的 success
上的匿名函数调用中,是否有更优雅的方法来定义 this
的范围(即不使用 that
)?
Is there a more elegant way of scoping this
in the anonymous function call on success
of the AJAX request (i.e. not using that
)?
例如:
var Foo = {
bar: function(id) {
var that = this;
$.ajax({
url: "www.somedomain.com/ajax_handler",
success: function(data) {
that._updateDiv(id, data);
}
});
},
_updateDiv: function(id, data) {
$(id).innerHTML = data;
}
};
var foo = new Foo;
foo.bar('mydiv');
使用调用但仍然必须命名父对象范围that
.
Using call but still have to name the parent object scope that
.
success: function(data) {
(function() {
this._updateDiv(id, data);
}).call(that);
}
推荐答案
在 jQuery 1.4 中,您有 $.proxy
方法,可以简单的写成:
In jQuery 1.4 you have the $.proxy
method, you can simply write:
//...
bar: function(id) {
$.ajax({
url: "someurl",
success: $.proxy(this, '_updateDiv')
});
},
//...
$.proxy
接受一个对象,该对象将用作 this
值,它可以接受字符串(该对象的成员)或函数,它将返回一个新函数,该函数始终具有特定的作用域.
$.proxy
takes an object, that will be used as the this
value and it can take either a string (a member of that object) or a function, and it will return a new function that will always have a particular scope.
另一种选择是 bind
函数,现在 ECMAScript 第五版标准的一部分是最好的:
Another alternative is the bind
function, now part of the ECMAScript Fifth Edition standard is the best:
//...
bar: function(id) {
$.ajax({
url: "someurl",
success: function(data) {
this._updateDiv(id, data);
}.bind(this)
});
},
//...
这个功能很快就会在本地实现,当 JavaScript 引擎完全实现 ES5 标准时,现在,你可以使用以下 8 行长的实现:
This function will be available natively soon, when JavaScript engines fully implement the ES5 standard, for now, you can use the following 8-line long implementation:
// The .bind method from Prototype.js
if (!Function.prototype.bind) { // check if native implementation available
Function.prototype.bind = function(){
var fn = this, args = Array.prototype.slice.call(arguments),
object = args.shift();
return function(){
return fn.apply(object,
args.concat(Array.prototype.slice.call(arguments)));
};
};
}
这篇关于在 jQuery 实用程序/ajax 方法中设置“this"的匿名函数范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!