返回

this, call, apply 和 bind 的精髓与区别

见解分享

JavaScript 中的 thiscall(), apply(), bind():深入解析

理解 this 对象

在 JavaScript 中,this 对象代表当前正在执行的函数的上下文环境。它并非固定不变,而是指向最后调用它的对象。这对于理解代码如何执行至关重要。

例如,考虑以下代码:

const obj = {
  name: 'John',
  getName: function() {
    return this.name;
  }
};

const getName = obj.getName;
console.log(getName()); // undefined

当调用 getName() 时,this 指向 window 对象,因为函数是在全局作用域中调用的。然而,当使用 obj.getName() 调用该函数时,this 指向 obj 对象,因为它是 getName() 函数所属的对象。

改变函数上下文

为了改变函数的执行上下文,可以使用 call(), apply(), bind() 这三个方法。

call() 方法

call() 方法允许显式设置函数的 this 值。其语法如下:

func.call(thisArg, arg1, arg2, ...)

其中:

  • func:要调用的函数
  • thisArg:要设置的 this
  • arg1, arg2, ...:要传递给函数的参数

示例:

const obj = {
  name: 'John'
};

function getName() {
  return this.name;
}

getName.call(obj); // John

apply() 方法

apply() 方法与 call() 类似,但参数必须是一个数组。其语法如下:

func.apply(thisArg, [args])

其中:

  • func:要调用的函数
  • thisArg:要设置的 this
  • args:要传递给函数的参数数组

示例:

const obj = {
  name: 'John'
};

function getName() {
  return this.name;
}

getName.apply(obj, ['Jane']); // John

bind() 方法

bind() 方法与 call()apply() 不同,它不会立即执行函数,而是返回一个新函数,该函数的 this 值被固定为指定的 this 值。其语法如下:

func.bind(thisArg, arg1, arg2, ...)

其中:

  • func:要调用的函数
  • thisArg:要设置的 this
  • arg1, arg2, ...:要传递给函数的参数

示例:

const obj = {
  name: 'John'
};

function getName() {
  return this.name;
}

const boundGetName = getName.bind(obj);
boundGetName(); // John

总结

thiscall(), apply(), bind() 是 JavaScript 中设置函数执行上下文环境的重要概念。它们的用法和区别如下:

方法 用途
this 获取当前函数的执行上下文对象
call() 显式设置函数的 this
apply() 显式设置函数的 this 值,参数为数组
bind() 返回一个新函数,该函数的 this 值被固定

常见问题解答

  1. 什么是 this 对象?

    • this 对象表示当前正在执行的函数的上下文环境。
  2. 如何改变函数的上下文?

    • 可以使用 call(), apply(), bind() 方法显式设置函数的上下文。
  3. call()apply() 的区别是什么?

    • call() 将参数逐个传递给函数,而 apply() 将参数作为一个数组传递给函数。
  4. 如何使用 bind()

    • bind() 创建一个新函数,该函数的 this 值被固定为指定的 this 值。
  5. 为什么 this 对象很重要?

    • this 对象允许函数访问其上下文对象,例如对象的属性和方法。