Lexical environment and function scope

前端 未结 3 1166
梦谈多话
梦谈多话 2020-12-04 06:43

Is lexical environment and scope in javascript one and the same thing?

3条回答
  •  感情败类
    2020-12-04 07:36

    Here's what the spec says about lexical environments:

    A Lexical Environment is a specification type used to define the association of Identifiers to specific variables and functions based upon the lexical nesting structure of ECMAScript code. A Lexical Environment consists of an Environment Record and a possibly null reference to an outer Lexical Environment.

    Based on that, I would say yes, that's what people are usually talking about when they say "scope".

    Although it could probably be argued that a "scope" is actually defined as a "Declarative Environment Record":

    Each declarative environment record is associated with an ECMAScript program scope containing variable and/or function declarations. A declarative environment record binds the set of identifiers defined by the declarations contained within its scope.

    If you think of a "scope" as a thing that contains bindings between identifiers and values, then the 2nd definition probably fits better. If you think of it as something that is aware of its ancestor scopes, then the first definition fits better.

    Edit: and a third option is "Execution Context".

提交回复
热议问题