博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
jQuery.proxy()代理、回调方法
阅读量:4042 次
发布时间:2019-05-24

本文共 1537 字,大约阅读时间需要 5 分钟。

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

·         jQuery.proxy( function, context )

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

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

·         jQuery.proxy( context, name )

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

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

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

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

看一下官方的例子:

01

var obj = {

02

name: "John",

 

03

test: function() {

04

alert( this.name );

 

05

$("#test").unbind("click", obj.test);

06

}

 

07

};

08

 

 

09

$("#test").click( jQuery.proxy( obj, "test" ) );

10

 

 

11

// 以下代码跟上面那句是等价的:

12

// $("#test").click( jQuery.proxy( obj.test, obj ) );

 

13

 

14

// 可以与单独执行下面这句做个比较。

 

15

// $("#test").click( obj.test );

再看一下jquery.proxy的源码:

01

 

04

jQuery.proxy = function( fn, proxy, thisObject ) {

 

05

    if ( arguments.length === 2 ) {

06

        // jQuery.proxy(context, name);

 

07

        if ( typeof proxy === "string" ) {

08

            thisObject = fn;

 

09

            fn = thisObject[ proxy ];

10

            proxy = undefined;

 

11

 

12

            

 

17

        }

18

        // jQuery.proxy(name, context);

 

19

        else if ( proxy && !jQuery.isFunction( proxy ) ) {

20

            thisObject = proxy;

 

21

            proxy = undefined;

22

        }

 

23

    }

24

    if ( !proxy && fn ) {

 

25

        

26

        proxy = function() {

 

27

            return fn.apply( thisObject || this, arguments );

28

        };

 

29

    }

30

    // Set the guid of unique handler to the same of original handler, so it can be removed

 

31

    if ( fn ) {

32

        proxy.guid = fn.guid = fn.guid || proxy.guid || jQuery.guid++;

 

33

    }

34

    // So proxy can be declared as an argument

 

35

    return proxy;

36

}

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

转载地址:http://pvqdi.baihongyu.com/

你可能感兴趣的文章
开发者必须知道的HTML5十五大新特性
查看>>
linux下IPTABLES配置详解
查看>>
Mysql错误:Table 'xxx'is marked as crashed and should be repaired
查看>>
memcached集群负载均衡
查看>>
memcached集群架构方面的问题
查看>>
理解 Node.js 里的 process.nextTick()
查看>>
如何从Eclipse导入github上的项目源码
查看>>
Node.js软肋之CPU密集型任务
查看>>
Linux pmap命令
查看>>
git回到上一版本命令
查看>>
Redis-benchmark使用总结
查看>>
apache+tomcat 均衡负载与集群中的session共享
查看>>
Node.js中的事件驱动编程详解
查看>>
mongodb 命令
查看>>
MongoDB基本使用
查看>>
mongodb管理与安全认证
查看>>
nodejs内存控制
查看>>
nodejs Stream使用中的陷阱
查看>>
windows 自制后台运行进程、exe开机自启动服务
查看>>
MongoDB 索引
查看>>