Skip to content

JS this 和 词法作用域?

JavaScript 中的 this词法作用域(lexical scope) 是两个容易混淆的概念,它们各自负责不同的作用范围和执行上下文。


🔍 一、什么是词法作用域(Lexical Scope)

✅ 定义:

词法作用域是指变量的作用范围在代码写下来的时候就已经决定了,取决于代码的位置(即定义的位置)。

js
function outer() {
  const a = 10;
  function inner() {
    console.log(a); // 能访问 a,是因为 inner 在 outer 中定义(词法作用域)
  }
  inner();
}
outer();

✅ 特点:

  • 函数定义时决定作用域;
  • 嵌套函数可以访问外部函数的变量;
  • 和调用位置无关,只看定义时位置。

🔁 二、什么是 this

✅ 定义:

this 是在函数被调用时绑定的,代表当前执行上下文的对象。

js
const obj = {
  a: 1,
  getA() {
    return this.a;
  }
};

obj.getA(); // 1,因为 this 是 obj

const get = obj.getA;
get(); // undefined 或 window.a(非严格模式),因为 this 是全局对象

✅ 特点:

  • this 的值由调用方式决定,而非定义位置;
  • 箭头函数不会绑定自己的 this,而是继承外层作用域的 this
  • 常见绑定方式有:默认绑定、隐式绑定、显式绑定、new 绑定等。

🧠 对比总结

特性this词法作用域(lexical scope)
决定时机调用时定义时
依赖上下文✅ 调用者决定❌ 与调用无关
箭头函数行为继承外层 this没有影响
使用用途访问对象成员变量解析与访问

🎯 实际例子说明差异

js
function outer() {
  const a = 100;

  return () => {
    console.log(a);     // 来自词法作用域
    console.log(this);  // 来自定义时所在的 this(箭头函数绑定外部)
  };
}

const obj = {
  fn: outer()
};

obj.fn(); // 词法作用域中的 a 始终是 100,this 是 window 或 undefined(严格模式)