0
我比任何其他更好奇。它如何将上下文传递给函数。它是否将该函数包装在对象中?我相信,有在JS这样做没有jQuery的代理jQuery代理如何工作
function abc(){
console.log(this.name);
}
var obj={name:"Something"};
$.proxy(abc,obj);
我怎样才能做到这一点没有jQuery的代理一些简单直接的代码?
我比任何其他更好奇。它如何将上下文传递给函数。它是否将该函数包装在对象中?我相信,有在JS这样做没有jQuery的代理jQuery代理如何工作
function abc(){
console.log(this.name);
}
var obj={name:"Something"};
$.proxy(abc,obj);
我怎样才能做到这一点没有jQuery的代理一些简单直接的代码?
没有jQuery的你可以使用bind:
var newFunction = abc.bind(obj);
如果你想与IE8兼容,你可以做
var newFunction = function(){ abc.call(obj) };
这里是jQuery的是如何做的:
// Bind a function to a context, optionally partially applying any
// arguments.
proxy: function(fn, context) {
var args, proxy, tmp;
if (typeof context === "string") {
tmp = fn[ context ];
context = fn;
fn = tmp;
}
// Quick check to determine if target is callable, in the spec
// this throws a TypeError, but we will just return undefined.
if (!jQuery.isFunction(fn)) {
return undefined;
}
// Simulated bind
args = core_slice.call(arguments, 2);
proxy = function() {
return fn.apply(context || this, args.concat(core_slice.call(arguments)));
};
// Set the guid of unique handler to the same of original handler, so it can be removed
proxy.guid = fn.guid = fn.guid || jQuery.guid++;
return proxy;
},
啊,当人们来来往往,并没有麻烦留下评论 –