JS中call()、apply()、bind()的区别及应用场景

 <button>点击</button>
  <script>
    // call,apply,bind都可以改变this
    //call方法 fn.call(thisArg,arg1,arg2...)
    //1:可以调用函数
    //2:实现继承
    //3:判断数据类型
    let persion={
      name:'迪丽热巴'
    }
    function fn(){
      console.log(this,123)
    }
    fn() //window
    fn.call(persion) //persion
    function Father(name,age){
      this.name = name
      this.age = age
    }
    function Son(name,age){
      Father.call(this,name,age)
    }
    let son = new Son("迪丽热巴",24)
    console.log(son)
    console.log(typeof([1,2]))
    console.log(Object.prototype.toString.call([1,2]))



    //apply方法 fn.apply(thisArg,[arg1,arg2...])
    //传递的参数必须是一个数组
    //Math.max.apply()
    function fn1(arg1,arg2){
      console.log(this,arg1,arg2)
    }
    fn1.apply(persion,["10","2"])
    let arr = [10,9,11,12,8]
    console.log(Math.max.apply(Math,arr))



    //bind方法 fn.bind(thisArg,arg1,arg2...)
    //不会调用
    //返回的是原函数改变this之后产生的新函数
    function fn2(name){
      console.log(this,name,22)
    }
    let f = fn2.bind(persion,"热巴")
    f()
    let btn = document.querySelector('button')
    btn.onclick = function(){
      this.disabled = true
      setTimeout(function(){
        this.disabled = false
      }.bind(this),3000)
    }
  </script>

相同点 : 三者都有改变this的指向问题 

区别:

1:call和apply都可以调用函数 

2:call和apply传递的参数不一样 call传递参数arg1... ,apply传递参数[agr1...]

3:bind不会调用函数

应用场景:

1:call用来继承

2:apply经常以数组有关,求最大值,最小值等

3:bind不调用函数,但是要改变this的指向 如定时器内部的this等

猜你喜欢

转载自blog.csdn.net/xy19950125/article/details/121124800