jQuery.proxy()代理、回调方法

来源:互联网 发布:单片机使用教程 编辑:程序博客网 时间:2024/06/03 06:42

jQuery.proxy(),接受一个函数,然后返回一个新函数,并且这个新函数始终保持了特定的上下文(context )语境。

  • jQuery.proxy( function, context )

    function将要改变上下文语境的函数。

    context函数的上下文语境(`this`)会被设置成这个 object 对象。

  • jQuery.proxy( context, name )

    context函数的上下文语境会被设置成这个 object 对象。

    name将要改变上下文语境的函数名(这个函数必须是前一个参数 ‘context’ 对象的属性)

这个方法通常在向一个元素上附加事件处理函数时,上下文语境实际是指向另一个对象的情况下使用。

另外,jQuery 能够确保即使你绑定的函数是经过 jQuery.proxy() 处理过的函数,你依然可以用原先的函数来正确地取消绑定。

看一下官方的例子:

var obj = {  name: "John",  test: function() {    alert( this.name );    $("#test").unbind("click", obj.test);  }}; $("#test").click( jQuery.proxy( obj, "test" ) ); // 以下代码跟上面那句是等价的:// $("#test").click( jQuery.proxy( obj.test, obj ) );// 可以与单独执行下面这句做个比较。// $("#test").click( obj.test );
再看一下jquery.proxy的源码:
/* jQuery 源码之 proxy: 使用 apply 形式, 执行回调函数.*/jQuery.proxy = function( fn, proxy, thisObject ) {    if ( arguments.length === 2 ) {        // jQuery.proxy(context, name);        if ( typeof proxy === "string" ) {            thisObject = fn;            fn = thisObject[ proxy ];            proxy = undefined;             /* 转化结果:                thisObject -> context                fn -> name                proxy -> undefined             */        }        // jQuery.proxy(name, context);        else if ( proxy && !jQuery.isFunction( proxy ) ) {            thisObject = proxy;            proxy = undefined;        }    }    if ( !proxy && fn ) {        /* 使用 proxy 保证 函数执行时, context 为指定值 */        proxy = function() {            return fn.apply( thisObject || this, arguments );        };    }    // Set the guid of unique handler to the same of original handler, so it can be removed    if ( fn ) {        proxy.guid = fn.guid = fn.guid || proxy.guid || jQuery.guid++;    }    // So proxy can be declared as an argument    return proxy;}

其实就是平常使用的的call和apply,大部分的时候作为回调使用。

原创粉丝点击