返回

手把手教你掌握 JavaScript 函数 call、apply 和 bind 方法

前端

概览

在 JavaScript 中,函数的调用方式有很多种,其中 call、apply 和 bind 都是非常常用的方法。这些方法允许你指定函数的执行上下文,从而改变函数中 this 的指向。理解并正确使用这些方法可以帮助你编写出更灵活、更健壮的代码。

方法详解

1. call 方法

call 方法的语法如下:

function.call(context, arg1, arg2, ...)

其中:

  • function :要调用的函数。
  • context :指定函数的执行上下文,即 this 关键字的指向。
  • arg1, arg2, ... :要传递给函数的参数。

call 方法的执行过程如下:

  1. 将函数设为对象的属性。
  2. 执行这个函数。
  3. 删除这个函数。

例如:

const person = {
  name: 'John',
  greet: function() {
    console.log(`Hello, my name is ${this.name}`);
  }
};

const anotherPerson = {
  name: 'Jane'
};

// 使用 call 方法改变函数的执行上下文
person.greet.call(anotherPerson); // 输出:Hello, my name is Jane

2. apply 方法

apply 方法的语法如下:

function.apply(context, [args])

其中:

  • function :要调用的函数。
  • context :指定函数的执行上下文,即 this 关键字的指向。
  • [args] :要传递给函数的参数,是一个数组。

apply 方法的执行过程与 call 方法基本相同,只是参数的传递方式不同。apply 方法将参数放在一个数组中传递给函数,而 call 方法则逐个传递参数。

例如:

const person = {
  name: 'John',
  greet: function() {
    console.log(`Hello, my name is ${this.name}`);
  }
};

const anotherPerson = {
  name: 'Jane'
};

// 使用 apply 方法改变函数的执行上下文
person.greet.apply(anotherPerson, ['Jane']); // 输出:Hello, my name is Jane

3. bind 方法

bind 方法的语法如下:

function.bind(context, arg1, arg2, ...)

其中:

  • function :要绑定的函数。
  • context :指定函数的执行上下文,即 this 关键字的指向。
  • arg1, arg2, ... :要预先传递给函数的参数。

bind 方法与 call 和 apply 方法不同,它不会立即执行函数,而是返回一个新的函数。这个新函数的执行上下文被绑定到给定的 context,并且预先传递的参数也已经绑定好了。

例如:

const person = {
  name: 'John',
  greet: function() {
    console.log(`Hello, my name is ${this.name}`);
  }
};

const anotherPerson = {
  name: 'Jane'
};

// 使用 bind 方法绑定函数的执行上下文
const boundGreet = person.greet.bind(anotherPerson);

// 执行绑定的函数
boundGreet(); // 输出:Hello, my name is Jane

区别比较

方法 执行过程 参数传递 返回值
call 将函数设为对象的属性 → 执行函数 → 删除函数 逐个传递参数 undefined
apply 将参数放在数组中传递给函数 → 执行函数 → 删除函数 数组 undefined
bind 返回一个新的函数,该函数的执行上下文被绑定到给定的 context,并且预先传递的参数也已经绑定好了 逐个传递参数 一个新的函数

总结

call、apply 和 bind 方法都是非常有用的 JavaScript 函数,它们允许你指定函数的执行上下文,从而改变函数中 this 关键字的指向。理解并正确使用这些方法可以帮助你编写出更灵活、更健壮的代码。

常见问题

1. 如何选择使用 call、apply 或 bind 方法?

  • call :当你知道要传递给函数的参数时,可以使用 call 方法。
  • apply :当你要传递给函数的参数是一个数组时,可以使用 apply 方法。
  • bind :当你想要创建一个新的函数,该函数的执行上下文被绑定到给定的 context,并且预先传递的参数也已经绑定好了时,可以使用 bind 方法。

2. 如果不传入参数,默认指向为 window?

如果在调用 call、apply 或 bind 方法时不传入 context 参数,那么默认指向为 window 对象。这是因为在 JavaScript 中,函数的默认执行上下文是 window 对象。