返回

手把手教你写call、apply、bind,原来一点也不难!

前端

函数调用:深入理解 call、apply 和 bind

什么是函数调用?

在 JavaScript 中,函数调用是让函数执行其内部代码的过程,同时还可以向函数传递参数。函数调用的基本语法如下:

function_name(arg1, arg2, ...);

其中:

  • function_name 是函数的名称。
  • arg1, arg2 等是传递给函数的参数。

call 和 apply

call()apply() 方法允许您指定函数的上下文对象(即 this 指向的对象)和参数。

call() 方法

call() 方法的语法如下:

function_name.call(context, arg1, arg2, ...);

其中:

  • function_name 是函数的名称。
  • context 是函数的上下文对象。
  • arg1, arg2 等是传递给函数的参数。

apply() 方法

apply() 方法的语法如下:

function_name.apply(context, [args]);

其中:

  • function_name 是函数的名称。
  • context 是函数的上下文对象。
  • [args] 是一个包含传递给函数的参数的数组。

bind() 方法

bind() 方法用于创建一个新的函数,该函数的上下文对象和参数都已指定。

bind() 方法

bind() 方法的语法如下:

function_name.bind(context, arg1, arg2, ...);

其中:

  • function_name 是函数的名称。
  • context 是函数的上下文对象。
  • arg1, arg2 等是传递给函数的参数。

区别和应用场景

call() 和 apply() 方法

  • call()apply() 方法都允许您改变函数的上下文对象和参数。
  • call() 方法逐个传递参数,而 apply() 方法将参数作为数组传递。

bind() 方法

  • bind() 方法创建了一个新的函数,其中上下文对象和参数都已绑定。
  • bind() 方法不会立即调用函数。

手写 call、apply 和 bind

以下是这些方法的手写实现:

Function.prototype.myCall = function (context, ...args) {
  context.fn = this;
  const result = context.fn(...args);
  delete context.fn;
  return result;
};

Function.prototype.myApply = function (context, args) {
  context.fn = this;
  const result = context.fn(...args);
  delete context.fn;
  return result;
};

Function.prototype.myBind = function (context, ...args) {
  const fn = this;
  return function (...bindArgs) {
    return fn.myApply(context, [...args, ...bindArgs]);
  };
};

注意:

  • 如果 call()apply() 方法的第一个参数为 nullundefined,则函数的上下文对象将变为全局对象(window 对象)。
  • bind() 方法返回一个新的函数,其中上下文对象和参数已绑定,但它不会立即调用该函数。

结论

call(), apply()bind() 方法是 JavaScript 中强大的函数调用方法。通过理解这些方法之间的差异和应用场景,您可以高效地使用 JavaScript 函数。

常见问题解答

1. 什么是函数上下文对象?
函数上下文对象是 this 关键字指向的对象。它决定了函数内部 this 关键字的行为。

2. 为什么我需要使用 call(), apply()bind()
这些方法允许您控制函数的上下文对象和参数,在需要更改这些值时非常有用。

3. call()apply() 方法有什么区别?
call() 方法逐个传递参数,而 apply() 方法将参数作为数组传递。

4. bind() 方法与其他方法有何不同?
bind() 方法创建一个新的函数,其中上下文对象和参数都已绑定,但它不会立即调用该函数。

5. 在什么时候使用 bind() 方法?
bind() 方法通常用于创建具有特定上下文对象或预定义参数的新函数。