代码之家  ›  专栏  ›  技术社区  ›  Magnus

通过遵循ECMAScript规范理解JavaScript super()调用

  •  0
  • Magnus  · 技术社区  · 6 年前

    class Parent {
      constructor() {}
    }
    
    class Child extends Parent {
      constructor() {
        super();
      }
    }
    

    因为我想弄清楚 super() 类构造函数中的调用起作用,我遵循以下顺序 ECMAScript

    1. new Child() 电话 ChildConstructor.[[Construct]]
    2. kind (早期设置 14.5.15 ),所以没有新的 this
    3. OrdinaryCallEvaluateBody 被称为 Child 类构造函数方法,其中 超级()
    4. super() 电话 ParentConstructor.[[Construct]] ,这让我们回到 ,只是 作为 基础
    5. 自从 是现在 基础 绑定被创建并绑定到 环境记录 新的 Parent
    6. 其余的 起源 Child.[[Construct]] 从第11步开始执行
    7. 最后, 子级。[[构造]] envRec.GetThisBinding

    问题

    这个 环境记录 对于 儿童 step 6 属于 子级。[[构造]] 捆绑( [[ThisBindingStatus]] 未初始化 GetThisBinding环境 在第8步中,我们应该尽我所能 ReferenceError as specified here ).

    我错过了什么?我好像不明白为什么 构造函数不会抛出错误,如果 [[ThisValue]] 构造函数已设置完毕。

    1 回复  |  直到 6 年前
        1
  •  1
  •   loganfsmyth    6 年前

    你错过了一步 super()

    1. newTarget GetNewTarget()
    2. 断言: Type(newTarget) 是对象。
    3. func 是吗? GetSuperConstructor() .
    4. argList ArgumentListEvaluation 属于 Arguments .
    5. ReturnIfAbrupt(argList) .
    6. result 是吗? Construct(func, argList, newTarget)
    7. thisER GetThisEnvironment( )
    8. 回来吗? thisER.BindThisValue(result) .

    6 电话 ParentConstructor.[[Construct]] 正如你提到的,但是第8步将设置 this 捆绑在 Child envRec.GetThisBinding 在终点跑 ChildConstructor.[[Construct]] ,和 会有约束力的