標籤:style blog http color io java ar strong 2014
定義和用法
$.proxy 方法接受一個已有的函數,並返回一個帶特定內容相關的新的函數。
該方法通常用於向上下文指向不同對象的元素添加事件。
| 參數 |
描述 |
| function |
要被調用的已有的函數。 |
| context |
函數所在的對象的名稱。 |
| name |
已有的函數,其上下文將被改變(應該是 context 對象的屬性)。 |
具體執行個體:
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指的是initItem12 // this.$item.click(function () {13 // alert($(this).css("width")); //這個this指的是item,結果:200px14 // that.aa();//alert(2)15 // });16 17 18 // this.$item.click($.proxy(function () {19 // this.aa();//結果alert(2);20 // }, this)); //這個this指的是initItem21 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裡面的私人name30 };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() 方法