this指向及this应用

1. 初识this

this:指的是调用当前方法(函数)的那个对象
alert(this);//object window
代码1:注意,此时弹出window,但是如果fn1();变成oBtn.οnclick=fn1;则弹出oBtn。
这里写图片描述

代码2:此时this指的是input;

<input id="btn2" type="button" onclick="alert(this);" value="按钮2"/>

2. 常见的this指向

function fn1(){
this
}
//fn1(); this=>window
oDiv.onclick=fn1;  this=>oDiv
oDiv.onclick=function (){
fn1();    //fn1()里的this=>window
}
<div onclick="this "></div>
//this=> div
<div onclick="fn1(); "></div>
//fn1();里的this=>window
alert(this); window
fn1(this);
function fn1(obj){
 obj=>window
}
oDiv.onclick=function(){
  this   //this指的oDiv
  fn1(this);  //this指的oDiv
}
function fn1(obj){obj=>oDiv}

3. 小例子1

<input type="button" value="按钮1"/>
<input type="button" value="按钮2"/>
<input type="button" value="按钮3"/>
<script>
window.onload=function(){
 var aBtn=document.getElementsByTagName('input');
        for(var i=0;i<aBtn.length;i++){
         aBtn[i].onclick=function(){
            this.style.background='yellow';//this指的是当前的aBtn
         }
 }
}
</script>
<script>
window.onload=function(){
 var aBtn=document.getElementsByTagName('input');
        for(var i=0;i<aBtn.length;i++){
            aBtn[i].onclick=function(){
               fn1();
            }
        }
        function fn1(){
          this//指的是window
        }
}
</script>

借用that可以使点一个按钮让其变颜色

<script>
window.onload=function(){
 var aBtn=document.getElementsByTagName('input');
 var that=null;
        for(var i=0;i<aBtn.length;i++){
            aBtn[i].onclick=function(){
               that=this;
               fn1();
            }
        }
        function fn1(){
          that.style.background='yellow';
        }
}
</script>
<script>
window.onload=function(){
 var aBtn=document.getElementsByTagName('input');
 var that=null;
        for(var i=0;i<aBtn.length;i++){
           aBtn[i].onclick=fn1;//fn1加()就会报错
        }
        function fn1(){
         // this=>aBtn[i]
          this.style.background='yellow';
        }
}
</script>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值