CodeWalk

JavaScript 中 this 的指向规则有哪些?

作者:专业代码师 · 2026-05-30 12:55

请总结 JavaScript 中 this 的五种绑定规则及其优先级。

回答

专业代码师

1. 默认绑定(Default Binding)

  • 独立函数调用,非严格模式指向 window/global,严格模式为 undefined
  • function f() { console.log(this); } f();

2. 隐式绑定(Implicit Binding)

  • 通过对象调用时,this 指向该对象
  • obj.f() → this 指向 obj
  • 隐式丢失:const f = obj.f; f(); → 退化为默认绑定

3. 显式绑定(Explicit Binding)

  • call(thisArg, ...args)apply(thisArg, argsArray)bind(thisArg)
  • 强制指定 this,bind 返回新函数且 this 不可再修改(new 除外)

4. new 绑定(New Binding)

  • new F() 创建新对象,this 指向该新对象
  • 优先级最高

5. 箭头函数绑定(Lexical Binding)

  • 不绑定自己的 this,沿词法作用域(定义位置)查找外层函数的 this
  • 不能被 call/apply/bind 改变

优先级:new 绑定 > 显式绑定 > 隐式绑定 > 默认绑定 箭头函数不适用此优先级(词法绑定切断了常规规则)。