jquery $.proxy 的使用執行個體詳解

來源:互聯網
上載者:User

在說$.proxy之前,先說一下this,this是JS對像,相當於一個局部變數,只在包含它的最裡面的一個function中啟作用。$.proxy在各個function之間起到了橋樑作用,並且不用重新賦值this,下面2個例子,詳細說一下$.proxy的用法。
1,this的範圍

$('#abc').click(function(){    //f1 
    console.log($(this).html());    //作用範圍f1,console.log有值 
 
    $.ajax({ 
       url: '1.php', 
       type: "get", 
       success:function()   //f2 
       { 
           console.log($(this).html()); //作用範圍f2,console.log為null 
       }//f2 
   }) 
}); //f1 
第二個console.log沒值的原因是,this被重新定義了。如果要使用第二個console.log有值,可以這樣,也是最常用的方法:

$('#abc').click(function(){    //f1 
    console.log($(this).html());    //作用範圍f1,console.log有值 
    var that=this; 
    $.ajax({ 
       url: '1.php', 
       type: "get", 
       success:function()   //f2 
       { 
           console.log($(that).html()); //作用範圍f2,console.log有值 
       }//f2 
   }) 
}); //f1 
2,$.proxy傳值

function test(){ 
   this.msg='this is test'; 
   this.onclick = function(){ 
      $('#abc').click(function(){ 
         this.getData();     //報錯,getData沒有定義 
      }) 
   } 
 
   this.onclick1 = function(){ 
      $('#abc').click($.proxy(this.getData,this));  //$.proxy的二個參數,第一個方法,第二個對像 
   } 
 
   this.onclick2 = function(){ 
      $('#abc').click($.proxy(this,"getData"));    //$.proxy二個參數,第一個對像,第二個方法名 
   } 
 
   this.getData=function(){ 
      console.log(this.msg); 
   } 
} 
 
//調用方法如下 
 
new test().onclick(); 
new test().onclick1(); 
new test().onclick2(); 
onclick:報錯是因為this範圍的問題,this範圍內,沒有getData方法,所以報錯。
onclick1和onclick2是一樣的,只不過是寫法不一樣,傳的參數不一樣而已。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.