返回

JS 中的 this 的全方位解析

前端

在 JavaScript 中,this 是一个,表示当前函数的执行环境。为了能够在函数体内获得当前运行环境,就定了一个 this 关键字。this 的值根据函数的调用方式和定义方式而定,它可以是全局对象、函数对象、DOM 元素等。

this 的作用域

this 的作用域是指 this 值可以被访问的范围。在 JavaScript 中,有两种作用域:全局作用域和局部作用域。全局作用域是整个脚本可以访问的范围,而局部作用域是函数内部可以访问的范围。

  • 全局作用域: this 指向 window 对象。
  • 局部作用域: this 指向函数内部的对象。

this 的执行环境

this 的执行环境是指 this 值所在的函数或代码块。在 JavaScript 中,有四种执行环境:

  • 全局执行环境: 在脚本顶层执行的代码。
  • 函数执行环境: 在函数内部执行的代码。
  • 对象执行环境: 在对象的方法内部执行的代码。
  • 箭头函数执行环境: 在箭头函数内部执行的代码。

this 的箭头函数

箭头函数(又称匿名函数)是 ES6 中引入的一种新的函数语法。箭头函数没有自己的 this 值,它总是继承外层函数的 this 值。

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

person.greet(); // 'John Doe'

const greet = () => {
  console.log(this.name);
};

greet(); // undefined

this 的 class

class 是 ES6 中引入的一种新的语法,用于定义类。class 中的方法默认绑定到类的实例上,因此 this 指向类的实例。

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

  greet() {
    console.log(this.name);
  }
}

const person = new Person('John Doe');
person.greet(); // 'John Doe'

this 的 bind、call 和 apply

bind、call 和 apply 是三个用于改变函数执行环境的方法。

  • bind: 创建一个新的函数,该函数的 this 值被绑定到指定的对象。
  • call: 立即执行一个函数,并将 this 值设置为指定的