返回

JS 基础系列 之 简单记忆 this 指向

前端

this 的指向:不变的规则

在 JavaScript 中,this 指向当前执行上下文的对象,它是一个动态的值,随着执行环境的不同而改变。为了深入理解 this 的指向,我们需要牢记以下不变的规则:

  1. 全局作用域中的 this 指向 window 对象。

    例如:

    console.log(this); // 输出:Window
    
  2. 函数体内的 this 指向函数所属的对象。

    例如:

    const person = {
      name: "John",
      greet() {
        console.log(this.name); // 输出:John
      }
    };
    
    person.greet();
    
  3. 构造函数中的 this 指向新创建的对象。

    例如:

    function Person(name) {
      this.name = name;
    }
    
    const person1 = new Person("John");
    console.log(person1.name); // 输出:John
    
  4. 使用 call、apply 或 bind 方法时,this 指向可以显式指定。

    例如:

    const person = {
      name: "John",
    };
    
    const greet = function () {
      console.log(this.name);
    };
    
    greet.call(person); // 输出:John
    

this 的指向:万变的应用

牢记不变的规则后,我们就可以灵活应对 this 指向在各种场景中的应用。下面是一些常见的案例:

  1. 事件处理程序中的 this 指向事件目标元素。

    例如:

    const button = document.querySelector("button");
    
    button.addEventListener("click", function () {
      console.log(this); // 输出:<button>元素
    });
    
  2. 箭头函数中的 this 指向其父级作用域中的 this。

    例如:

    const person = {
      name: "John",
      greet() {
        const innerFunction = () => {
          console.log(this.name); // 输出:John
        };
    
        innerFunction();
      }
    };
    
    person.greet();
    
  3. 使用 bind 方法可以将函数的 this 指向绑定到特定对象。

    例如:

    const person = {
      name: "John",
    };
    
    const greet = function () {
      console.log(this.name);
    };
    
    const boundGreet = greet.bind(person);
    
    boundGreet(); // 输出:John
    

总结

this 指向是一个动态值,它随着执行环境的不同而改变。掌握不变的规则并理解万变的应用,是编写有效 JavaScript 代码的关键。通过对 this 指向的深入理解,我们可以更轻松地处理复杂的 JavaScript 程序。