返回

程序调教:理清thisBinding,掌控JavaScript的脉搏

前端

前言

在上一篇文章《JS夯实之执行上下文与词法环境》中,我们探讨了词法环境的创建过程,略过了thisBinding绑定的陈述。this的指向问题,不管是在面试还是业务工作中,都是经久不衰的“坑”。只要熟记四条准则,不论多么复杂的场景,你都能正确判断出this的指向。

概述:thisBinding的四大准则

thisBinding的绑定规则主要有四条:

  1. 隐式绑定: 当函数被调用时,this指向调用它的对象。
  2. 显式绑定: 使用call()、apply()或bind()方法可以显式地将this绑定到指定的对象。
  3. new绑定: 当使用new创建对象时,this指向新创建的对象。
  4. 默认绑定: 如果函数在没有明确的this绑定情况下被调用,this指向全局对象(在浏览器中为window对象)。

一、隐式绑定

隐式绑定是最常见的this绑定方式。当函数被调用时,this指向调用它的对象。例如,以下代码中,this指向的是person对象:

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

person.greet(); // 输出:Hello, my name is John Doe

二、显式绑定

显式绑定允许我们使用call()、apply()或bind()方法将this绑定到指定的对象。例如,以下代码中,我们使用call()方法将this绑定到person对象:

const person = {
  name: 'John Doe'
};

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

greet.call(person); // 输出:Hello, my name is John Doe

三、new绑定

当使用new关键字创建对象时,this指向新创建的对象。例如,以下代码中,我们使用new关键字创建了一个Person对象,this指向该对象:

function Person(name) {
  this.name = name;

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

const person = new Person('John Doe');

person.greet(); // 输出:Hello, my name is John Doe

四、默认绑定

如果函数在没有明确的this绑定情况下被调用,this指向全局对象(在浏览器中为window对象)。例如,以下代码中,this指向window对象:

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

greet(); // 输出:Hello, my name is undefined

结语

熟练掌握thisBinding的绑定规则,是JavaScript开发人员必备的基础技能之一。通过理解这四条准则,你将能够轻松应对this指向相关的各种疑难杂症,编写出更加健壮和可维护的代码。