Skip to content

JS深入浅出 - 确定 this 对象指向 #6

Open
@jtwang7

Description

@jtwang7

JS深入浅出 - 确定 this 对象指向

参考文章:
嗨,你真的懂this吗?

绑定优先级

new 绑定 > 显式绑定 > 隐式绑定 > 默认绑定

具体过程

  1. 函数是否通过 new 绑定, 若是, 则 this 绑定创建的实例对象;
  2. 函数是否通过 call, apply, bind 绑定, 若是, 则 this 绑定第一参数指定的对象;
  3. 函数是否在某个上下文对象中调用(隐式绑定), 若是, this 绑定该上下文对象, 一般是 obj.foo(), 若对象链式调用, this 指向最近的调用上下文对象;
  4. 如果以上都不是, 那么使用默认绑定; 如果在严格模式下, 则绑定到 undefined, 否则绑定到全局对象;
  • null / undefined 作为 this 的绑定对象传入 call, apply, bind 会被忽略(无效), 此时应用默认绑定规则。
  • 如果是箭头函数, 箭头函数的 this 继承的是外层词法作用域的 this,箭头函数本身没有 this 对象。

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions