0
点赞
收藏
分享

微信扫一扫

bind指向

码农K 2022-03-26 阅读 119
javascript

bind

  1. 不会调用原来的函数,可以改变原来函数内部的this指向
  2. 返回的是原函数改变this后产生的新函数
  3. 如果有的函数我们不需要立即调用,但是又把想改变这个函数内部的this指向,此时用bind
  4. 我们有一个按钮,当我们点击了之后,就禁用这个按钮,3秒钟之后开启这个按钮
var btn = document.querySelector('button');
btn.onclick = function(){
    this.disabled = true; //这个this指向的是btn这个按钮
        // var that = this;
    setTimeout(function(){
        //定时器函数里面的this指向的是window
        this.disabled = false;  //此时指向的是btn
    }.bind(this),3000) //这个this指向的是btn 这个对象
} 

多个按钮指向

var btns = document.querySelectorAll("button");
for(var i = 0;i<btns.length;i++){
    btn[i].onclick = function(){
        this.disabled = true;
        setTimeout(function(){
            this.disabled = false
        }.bind(this),200);
    }
}
举报

相关推荐

0 条评论