Skip to content

apply、call、bind

apply

apply是JavaScript函数对象的一个方法,它允许你在调用函数时将一个数组或类数组对象作为参数传递进去。语法如下:

javascript
function.apply(thisArg, [argsArray])
  • thisArg: 在函数执行时指定的 this 值。
  • argsArray: 一个数组或者类数组对象,其中的元素将作为参数传递给函数。

call

callapply类似,也是用于调用函数,但是参数的传递方式略有不同。语法如下:

javascript
function.call(thisArg, arg1, arg2, ...)
  • thisArg: 在函数执行时指定的 this 值。
  • arg1, arg2, ...: 传递给函数的参数列表。

bind

bind方法会创建一个新函数,称为绑定函数。当调用这个绑定函数时,绑定函数会以创建它时传入bind方法的第一个参数作为this值,后续的参数将作为实际参数传递给原函数。bind并不会立即执行,而是返回一个绑定了指定this的新函数。语法如下:

javascript
function.bind(thisArg, arg1, arg2, ...)
  • thisArg: 在函数执行时指定的 this 值。
  • arg1, arg2, ...: 传递给函数的参数列表。

区别

  • applycall的区别仅在于参数的传递方式,一个是数组,一个是逐个传递。
  • bind方法会创建一个新函数,并永久绑定指定的this值,而applycall则是立即调用原函数。
方法语法参数传递方式立即执行返回新函数
applyfunction.apply(thisArg, argsArray)数组或类数组对象
callfunction.call(thisArg, arg1, arg2, ...)逐个传递
bindfunction.bind(thisArg, arg1, arg2, ...)逐个传递(延迟执行)是,返回新函数

举例说明

使用apply

javascript
function greet(name) {
  console.log(`Hello, ${name}! I am ${this.title}`);
}

const context = { title: 'ChatGPT' };
const args = ['User'];

greet.apply(context, args);

使用call

javascript
function greet(name) {
  console.log(`Hello, ${name}! I am ${this.title}`);
}

const context = { title: 'ChatGPT' };

greet.call(context, 'User');

使用bind

javascript
function greet(name) {
  console.log(`Hello, ${name}! I am ${this.title}`);
}

const context = { title: 'ChatGPT' };
const boundGreet = greet.bind(context);

boundGreet('User');