this指向的改变(重点)

this指向的改变(重点)

       this含义--当前对象:指事件的调用者 或 方法的调用者。this指向直接绑定它的对象。

            一般函数的回调函数中的this指向window。事件监听除外。

 改变匿名函数的this指向:bind(this指向的对象);bind(this);或者再var that(也可以其他变量名)=this;

        this的指向:bind(this):可以改变匿名函数的指向。

 案例:

    var oDiv = document.getElementById("oDiv");

    setTimeout(function(){

       this.style.display = "none";

    }.bind(oDiv),3000);

    document.onclick = function(){

扫描二维码关注公众号,回复: 5208998 查看本文章

this.style.display = "none";

    }.bind(oDiv);

    改变非匿名函数的this的指向:apply( )或 call( )。

apply( ) 或 call( ):函数名.apply( 函数体内部this指向的对象 )。函数调用时改变this的指向。

    案例:

        var oDiv = document.getElementById("oDiv");

    function fn(){

        alert(this);

    }

    fn.apply( oDiv );

fn.call( oDiv );

     注意:使用匿名函数的都不能使用call( ),apply( )改变this指向,箭头函数也不可以改变。

        箭头函数中没有this,箭头函数中的this继承父级而来,用bind( )也不可以改变指向。

猜你喜欢

转载自blog.csdn.net/weixin_34216107/article/details/87560304