在jQuery实用程序/ ajax方法中设置'this'的匿名函数范围 [英] Setting anonymous function scope of 'this' in jQuery utility / ajax methods
问题描述
如此博客文章中所述,您可以设置<$的范围c $ c>这个在Javascript中的匿名函数中。
As noted in this blog post you can set the scope of this
in an anonymous function in Javascript.
是否有更优雅的方法 this
在AJAX请求的成功
的匿名函数调用中(即不使用
)?
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');
使用调用但仍需要命名父对象范围
。
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
获取一个对象,该对象将用作此
值,它可以采用字符串(该对象的成员)或一个函数,它将返回一个始终具有特定范围的新函数。
$.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屋!