返回

This 指向深入探究:以第三种视角剖析其精髓

前端

理解 "this" 的显示绑定

在 JavaScript 中,"this" 指向表示当前执行代码的上下文对象。显示绑定允许我们明确指定 "this" 指向,即使在函数调用时被改变。这在处理继承、回调函数和其他涉及 "this" 指向的复杂场景时非常有用。

三种显示绑定方法

JavaScript 提供了三种显示绑定方法:apply、call 和 bind。它们的主要区别在于参数传递方式:

  • apply(thisArg, argsArray) :将 "this" 指向设置为 thisArg,并以数组形式传递参数。
  • call(thisArg, arg1, arg2, ...) :将 "this" 指向设置为 thisArg,并按顺序传递参数。
  • bind(thisArg, arg1, arg2, ...) :创建一个新函数,该函数的 "this" 指向固定为 thisArg,并可以预先设置参数。

应用场景示例

继承

显示绑定可以用于实现 JavaScript 中的继承。通过将父类的函数应用于子类实例,子类可以访问并使用父类的属性和方法:

class Parent {
  constructor(name) {
    this.name = name;
  }

  greet() {
    console.log(`Hello, my name is ${this.name}.`);
  }
}

class Child extends Parent {
  constructor(name, age) {
    super(name);
    this.age = age;
  }

  greet() {
    // 使用 apply 绑定 "this" 指向为 Child 实例
    super.greet.apply(this);
    console.log(`I'm ${this.age} years old.`);
  }
}

const child = new Child('John', 25);
child.greet(); // 输出:"Hello, my name is John.";"I'm 25 years old."

回调函数

显示绑定也可以用于确保回调函数中的 "this" 指向正确。例如,考虑一个事件处理程序,它应该访问外部函数的 "this" 指向:

function outerFunction() {
  const self = this; // 保存 "this" 指向

  document.addEventListener('click', function() {
    // 使用 call 绑定 "this" 指向为 outerFunction
    outerFunction.call(self);
  });
}

const obj = {
  name: 'Object',
  outerFunction
};

obj.outerFunction(); // 输出:"Object"(正确的 "this" 指向)

创建新函数

bind 方法可以创建新函数,该函数的 "this" 指向固定为指定值。这在创建部分应用函数或柯里化函数时非常有用:

function add(x, y) {
  return x + y;
}

// 创建一个预先设置第一个参数为 10 的新函数
const add10 = add.bind(null, 10);

// 调用 add10,只需提供第二个参数即可
console.log(add10(5)); // 输出:15

总结

显示绑定是 JavaScript 中控制 "this" 指向的强大工具。通过使用 apply、call 和 bind 方法,我们可以明确指定 "this" 指向,解决各种复杂场景。理解和熟练运用显示绑定是成为一名精通 JavaScript 开发人员的重要技能。