码迷,mamicode.com
首页 > Web开发 > 详细

jQuery 之$.proxy() 方法

时间:2014-09-11 17:07:42      阅读:207      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   color   io   java   ar   strong   2014   

定义和用法

$.proxy 方法接受一个已有的函数,并返回一个带特定上下文的新的函数。

该方法通常用于向上下文指向不同对象的元素添加事件。


参数描述
function 要被调用的已有的函数。
context 函数所在的对象的名称。
name 已有的函数,其上下文将被改变(应该是 context 对象的属性)。

 

 

 

bubuko.com,布布扣

具体实例:

 1 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
 2 <html xmlns="http://www.w3.org/1999/xhtml">
 3 <head>
 4     <title></title>
 5     <script src="Scripts/jquery-1.4.1.min.js" type="text/javascript"></script>
 6     <script type="text/javascript">
 7         $(function () {
 8             var initItem = function () {
 9                 this.$item = $("<div style=‘width:200px;height:100px;background:#ccc;‘></div>");
10                 this.initClick = function () {
11                     var that = this; //这个this指的是initItem
12 //                    this.$item.click(function () {
13 //                        alert($(this).css("width")); //这个this指的是item,结果:200px
14 //                        that.aa();//alert(2)
15 //                    });
16 
17 
18 //                    this.$item.click($.proxy(function () {
19 //                        this.aa();//结果alert(2);
20 //                    }, this)); //这个this指的是initItem
21 
22                     var o = {
23                         name: "wowoowwo",
24                         test: function () {
25                             alert(this.name);
26                         }
27                     };
28                     // this.$item.click($.proxy(bb.test, bb));
29                     this.$item.click($.proxy(o, "test"));//$.proxy()用这个代理可以访问对象o里面的私有name
30                 };
31                 this.appendH = function () {
32                     $(".main").append(this.$item);
33                 };
34                 this.init = function () {
35                     this.initClick();
36                     this.appendH();
37                 };
38                 this.aa = function () {
39                     alert(2);
40                 };
41                 this.init();
42             }
43             initItem();
44         })
45     </script>
46 </head>
47 <body>
48 <div class="main"></div>
49 </body>
50 </html>

 

jQuery 之$.proxy() 方法

标签:style   blog   http   color   io   java   ar   strong   2014   

原文地址:http://www.cnblogs.com/dean-Wei/p/3966770.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!