Where are arguments positioned in the lexical environment?

偶尔善良 提交于 2020-06-24 12:52:42

问题


The following code always prints the argument passed in to parameter a, regardless of the presence of a variable with the same name.

Presumably because parameter identifiers are bound separately to variables in scope. Where are they positioned? Are they in the lexical environment?

function foo(a, b = () => a) {
  var a = 1
  console.log(b())
}
foo() // undefined
foo(2) // 2

Is it that var declarations end up in the special VariableEnvironment, while parameters are positioned in the LexicalEnvironment? And let and const avoid conflict by making redefinition an early error?

Relevant also:

  • 8.3.2 ResolveBinding(name [, env])
  • 8.1.1 Environment Records

回答1:


In the event that any default values are present, a separate environment record is created for parameters.

The semantics of functions declared in this position are such that this environment record defines their local scope. A note in the spec (see clause 28) says:

NOTE: A separate Environment Record is needed to ensure that closures created by expressions in the formal parameter list do not have visibility of declarations in the function body.

More from the spec:

When an execution context is established for evaluating an ECMAScript function a new function Environment Record is created and bindings for each formal parameter are instantiated in that Environment Record. Each declaration in the function body is also instantiated. If the function's formal parameters do not include any default value initializers then the body declarations are instantiated in the same Environment Record as the parameters. If default value parameter initializers exist, a second Environment Record is created for the body declarations. Formal parameters and functions are initialized as part of FunctionDeclarationInstantiation. All other bindings are initialized during evaluation of the function body.

In the absence of default arguments, therefore, I deduce that one of the pre-existing lexical environments (VariableEnvironment or LexicalEnvironment) is used for parameter bindings. Maybe.



来源:https://stackoverflow.com/questions/61208843/where-are-arguments-positioned-in-the-lexical-environment

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!