最新下载
热门教程
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
jquery $.proxy 的使用实例详解
时间:2022-06-25 17:30:54 编辑:袖梨 来源:一聚教程网
在说$.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是一样的,只不过是写法不一样,传的参数不一样而已。
相关文章
- 我的常州怎么查社保卡余额 我的常州查询医保卡余额方法 05-06
- 天刀共鸣技能搭配攻略(掌握共鸣技能,提升天刀战斗实力) 05-06
- 《Neverness To Everness》周年庆委托任务在哪里介绍 05-06
- 纳米ai怎么修改资料 纳米ai修改资料方法 05-06
- 月蚀技能攻略(掌握月蚀技能,成为真正的黑暗之王!) 05-06
- 纳米ai怎么静音 纳米ai静音方法 05-06