jquery有相同的dojo.hitch()吗?
请原谅我的无知,因为我对jquery并不熟悉。 有没有相当于dojo.hitch() ? 它返回一个保证在给定范围内执行的函数。
– 编辑 – 根据要求,这是一个例子。 我经常使用hitch来确保在正确的对象中执行回调。 例如,假设我有一个名为doSomethingAsync
的实用程序方法,我将其传递给回调函数。 有了故障,即使实用程序方法执行ajax调用等,我也可以确保函数在特定范围内执行:
expectedScopeObj = { flag: true, callback: function(){console.debug(this.flag);}, main: function() { // without hitch the callback function would not find flag core.util.doSomethingAsync(dojo.hitch(this, this.callback)); } }
没有故障,回调函数可能在不同的范围内执行,并且在未定义this.flag
会抛出错误。 但是,有了execptedScopeObj
,它可以保证在execptedScopeObj
执行。
我知道这已得到回答,但不正确。 我相信jQuery.proxy
正是你要找的。
UPDATE
很多年后,经过大量的JavaScript工作,并且在剥离了我对jQuery的使用后,由于浏览器兼容性问题变得不那么重要,我建议使用Function.prototype.bind
不是jQuery.proxy
,正如@bobince建议的那样 。 虽然这仍然是原始问题的正确答案,但我觉得有义务引导人们使用vanilla解决方案,而不是依赖于jQuery。
[ 管理员编辑 :请注意下面更受欢迎的答案.- danorton]
我会选择function.bind
,这将是在未来版本的JavaScript中执行此操作的标准方法。 除了修复this
,它还允许您将参数传递给目标函数。
在所有浏览器本地支持它之前,您可以自己破解支持 。
不,至少在1.3.2中,因为我不知道1.4。 但是,有一些插件 :
(function($) { $.fn.hitch = function(ev, fn, scope) { return this.bind(ev, function() { return fn.apply(scope || this, Array.prototype.slice.call(arguments)); }); }; })(jQuery);
bobince提到的function.bind是一个非常有用的工具。 你可以用它来简单地重写hitch函数:
// 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.hitch = function(scope, fn) { if (typeof fn == "string") fn = scope[fn]; if (fn && fn.bind) return fn.bind(scope); };
至少基于你链接的doc页面,这就是我看到函数工作的方式……
//why not just: (function($){ $.hitch = function(scope, fn){ return function(){ return fn.apply(scope, arguments); } } })(JQuery); //This works exactly like Dojo's hitch from what I can tell.
/** * This is for simulate dojo.hitch. * @param $ */ (function($) { $.hitch = function(context, func) { var args = Array.prototype.slice.call(arguments, 2/*Remove context, and func*/); return function() { return func.apply(context, Array.prototype.concat.call(args, arguments)); }; }; })(jQuery);
在我看来,Dojo中的故障更加复杂,
例如,
function f(a,b,c){return a+b*c} var newF = hitch(null,f,1,undefined,3); newF(2) /*1+2*3*/