在說$.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是一樣的,只不過是寫法不一樣,傳的參數不一樣而已。