call、apply、bind区别和应用场景

327 阅读2分钟

call方法

改变函数内部this指向

call()方法调用一个对象。简单理解为调用函数的方式,但是它可以改变函数的this指向。

写法:fun.call(thisArg, arg1, arg3, ...) // thisArg为想要指向的对象,arg1,arg3为参数

call 的主要作用也可以实现继承

function Person(uname, age) {

    this.uname = uname;

    this.age = age;

  }

  function Son(uname, age) {

    Person.call(this, uname, age);

  }

  var son = new Son("zhang", 12);

  console.log(son);

apply方法

apply()方法调用一个函数。简单理解为调用函数的方式,但是它可以改变函数的this指向。

写法:fun.apply(thisArg, [argsArray])

1.thisArg:在fun函数运行时指定的this值

2.argsArray:传递的值,必须包含在数组里面

3.返回值就是函数的返回值,因为他就是调用函数

apply的主要应用,比如可以利用apply可以求得数组中最大值

const arr = [1, 22, 3, 44, 5, 66, 7, 88, 9];

const max = Math.max.apply(Math, arr);

console.log(max);

bind方法

bind()方法不会调用函数,但是能改变函数内部this指向

写法:fun.bind(thisArg, arg1, arg2, ...)

1.thisArg:在fun函数运行时指定的this值

2.arg1,arg2:传递的其他参数

3.返回由指定的this值和初始化参数改造的原函数拷贝

var o = {

    name: "lisa"

};

function fn() {

    console.log(this);

}

var f = fn.bind(o);

f();

bind应用 如果有的函数我们不需要立即调用,但是又需要改变这个函数的this指向,此时用bind再合适不过了

const btns = document.querySelectorAll("button");

for (let i = 0; i < btns.length; i++) {

    btns[i].onclick = function() {

      this.disabled = true;

      setTimeout(

        function() {

          this.disabled = false;

        }.bind(this),

        2000

      );

    };

}

call、apply、bind 总结

相同点:

1.都可以改变函数内部的this指向。

区别点:

1.call 和 apply 会调用函数,并且改变函数内部this指向。

2.call 和 apply 传递的参数不一样,call 传递参数arg1,arg2...形式 apply 必须数组形式[arg]

3.bind 不会调用函数,可以改变函数内部this指向。

主要应用场景:

1.call 经常做继承。

2.apply 经常跟数组有关系,比如借助于数学对象实现数组最大值最小值。

3.bind 不调用函数,但是还想改变this指向,比如改变定时器内部的this指向。