this指向及应用

来源:互联网 发布:淘宝网如何盈利模式 编辑:程序博客网 时间:2024/06/15 01:11

this:指的是调用当前方法(函数)的那个对象

this指向(常见情况):

 function fn1(){

this   

}

1>

fn1();    //this=>window

2>

oDiv.onclick =fn1;    //this=>oDiv

3>

oDiv.onclick=function(){

      fn1();              //fn1()里的this=>window

};

4>

oDiv.onclick=function(){

     this                 //this=>oDiv

}

5>

<div onclick=" this "></div>   //this=>div

6>

<div onclick="this fn1();"></div>    //this=>window

this应用实例:

1>

window.onload=function(){

var aBtn = ducument.getElementsByTagName("input");

        for(var i=0;i<aBtn.length;i++){

aBtn[i].onclick=function(){

       this.style.background='yellow';//this=>aBtn,点击按钮变为黄色

};

}

};

如果把this换一个位置:

window.onload=function(){

var aBtn = ducument.getElementsByTagName("input");

        for(var i=0;i<aBtn.length;i++){

aBtn[i].onclick=function(){

              fn1();

};

}

        function fn1(){

this    //this=>window,并没有指向aBtn,所以写this.style.background='yellow';不会改变样式

}

};

解决方法:

    我们写一个单词,并让他的值为空

    var that = null;


      找到当前按钮,并把this放到that里存起来:

       aBtn[i].onclick=function(){

that=this

                fn1();

}

     调用fn1到时候找that

      function fn1(){

that.style.background='yellow';                 //实现效果

}

2>

window.onload=function(){

var aBtn = ducument.getElementsByTagName("input");

        for(var i=0;i<aBtn.length;i++){

               aBtn[i].onclick=fn1;

};

}

        function fn1(){

                 this.style.background=''yellow;    //this=>aBtn,因为在for循环中,fn1被aBtn调用了,点击按钮变为黄色

}

};


原创粉丝点击