JavaScript call、apply、bind 详解

21 阅读1分钟

前言

callapplybind是 JavaScript 中用来显式改变this的三个常用方法。 它们既是开发中常见工具,也是面试高频考点。


一、为什么需要 call、apply、bind?

有时候我们希望一个函数在执行时,this指向指定对象。

例如:

function say() {
  console.log(this.name);
}

const obj = {
  name: 'Tom'
};

如果直接调用:

say();

此时this不会指向obj。所以我们需要:

say.call(obj);

二、call

call会立即执行函数,并且第一个参数就是指定的this

function say(age) {
  console.log(this.name, age);
}

const obj = { name: 'Tom' };

say.call(obj, 18); // Tom 18

三、apply

applycall类似,也会立即执行函数。区别在于参数形式不同:

  • call:一个一个传参数

  • apply :参数放在数组里传

function say(age, city) {
  console.log(this.name, age, city);
}

const obj = { name: 'Tom' };

say.apply(obj, [18, 'Beijing']); // Tom 18 Beijing

四、bind

bind不会立即执行函数,而是返回一个新的函数,这个新函数的

this已经被绑定好了。

function say(age) {
  console.log(this.name, age);
}

const obj = { name: 'Tom' };

const fn = say.bind(obj, 18);
fn(); // Tom 18

五、三者区别总结

相同点

  • 都可以改变函数执行时的 this

不同点

call

  • 立即执行
  • 参数逐个传

apply

  • 立即执行
  • 参数数组传

bind

  • 不立即执行
  • 返回新函数

六、常见使用场景

1)借用方法

const arrLike = { 0: 'a', 1: 'b', length: 2 };
const arr = Array.prototype.slice.call(arrLike);

console.log(arr); // ['a', 'b']

2)绑定 this

const obj = {
  name: 'Tom',
  say() {
    console.log(this.name);
  }
};

setTimeout(obj.say.bind(obj), 1000);

七、总结

callapplybind的核心作用就是:

显式指定函数执行时的 this。

记忆口诀:

  • call :立即调用,参数逐个传

  • apply:立即调用,参数数组传

  • bind:不立即调用,返回新函数