jquery代理如何工作

时间:2013-07-31 17:45:15

标签: javascript jquery

我比其他任何事都更好奇。它是如何将上下文传递给函数的。它是否将函数包装在对象中?我确信在没有jquery proxy

的js中有一些简单的直接代码
function abc(){
  console.log(this.name);
}
var obj={name:"Something"};
$.proxy(abc,obj);

如果没有jquery代理,我怎么能这样做?

1 个答案:

答案 0 :(得分:4)

如果没有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;
},