15 ECMAScript 语言:函数与类

Note

各种 ECMAScript 语言元素会导致创建 ECMAScript 函数对象10.2)。对此类函数的求值从执行其 [[Call]] 内部方法开始(10.2.1)。

15.1 参数列表

语法

UniqueFormalParameters[Yield, Await] : FormalParameters[?Yield, ?Await] FormalParameters[Yield, Await] : [empty] FunctionRestParameter[?Yield, ?Await] FormalParameterList[?Yield, ?Await] FormalParameterList[?Yield, ?Await] , FormalParameterList[?Yield, ?Await] , FunctionRestParameter[?Yield, ?Await] FormalParameterList[Yield, Await] : FormalParameter[?Yield, ?Await] FormalParameterList[?Yield, ?Await] , FormalParameter[?Yield, ?Await] FunctionRestParameter[Yield, Await] : BindingRestElement[?Yield, ?Await] FormalParameter[Yield, Await] : BindingElement[?Yield, ?Await]

15.1.1 Static Semantics: 早期错误

UniqueFormalParameters : FormalParameters FormalParameters : FormalParameterList Note

FormalParameterList 中,同一个 BindingIdentifier 出现多次,仅在函数具有简单参数列表且未在严格模式代码中定义时才被允许。

15.1.2 Static Semantics: ContainsExpression

The syntax-directed operation ContainsExpression takes no arguments and returns 一个布尔值. It is defined piecewise over the following productions:

ObjectBindingPattern : { } { BindingRestProperty }
  1. 返回 false
ObjectBindingPattern : { BindingPropertyList , BindingRestProperty }
  1. 返回 BindingPropertyListContainsExpression
ArrayBindingPattern : [ Elisionopt ]
  1. 返回 false
ArrayBindingPattern : [ Elisionopt BindingRestElement ]
  1. 返回 BindingRestElementContainsExpression
ArrayBindingPattern : [ BindingElementList , Elisionopt ]
  1. 返回 BindingElementListContainsExpression
ArrayBindingPattern : [ BindingElementList , Elisionopt BindingRestElement ]
  1. hasBindingElementListContainsExpression
  2. 如果 hastrue,返回 true
  3. 返回 BindingRestElementContainsExpression
BindingPropertyList : BindingPropertyList , BindingProperty
  1. hasBindingPropertyListContainsExpression
  2. 如果 hastrue,返回 true
  3. 返回 BindingPropertyContainsExpression
BindingElementList : BindingElementList , BindingElisionElement
  1. hasBindingElementListContainsExpression
  2. 如果 hastrue,返回 true
  3. 返回 BindingElisionElementContainsExpression
BindingElisionElement : Elisionopt BindingElement
  1. 返回 BindingElementContainsExpression
BindingProperty : PropertyName : BindingElement
  1. hasPropertyNameIsComputedPropertyKey
  2. 如果 hastrue,返回 true
  3. 返回 BindingElementContainsExpression
BindingElement : BindingPattern Initializer
  1. 返回 true
SingleNameBinding : BindingIdentifier
  1. 返回 false
SingleNameBinding : BindingIdentifier Initializer
  1. 返回 true
BindingRestElement : ... BindingIdentifier
  1. 返回 false
BindingRestElement : ... BindingPattern
  1. 返回 BindingPatternContainsExpression
FormalParameters : [empty]
  1. 返回 false
FormalParameters : FormalParameterList , FunctionRestParameter
  1. 如果 FormalParameterListContainsExpressiontrue,返回 true
  2. 返回 FunctionRestParameterContainsExpression
FormalParameterList : FormalParameterList , FormalParameter
  1. 如果 FormalParameterListContainsExpressiontrue,返回 true
  2. 返回 FormalParameterContainsExpression
ArrowParameters : BindingIdentifier
  1. 返回 false
ArrowParameters : CoverParenthesizedExpressionAndArrowParameterList
  1. formals 为被 CoverParenthesizedExpressionAndArrowParameterList 覆盖ArrowFormalParameters
  2. 返回 formalsContainsExpression
AsyncArrowBindingIdentifier : BindingIdentifier
  1. 返回 false

15.1.3 Static Semantics: IsSimpleParameterList

The syntax-directed operation IsSimpleParameterList takes no arguments and returns 一个布尔值. It is defined piecewise over the following productions:

BindingElement : BindingPattern
  1. 返回 false
BindingElement : BindingPattern Initializer
  1. 返回 false
SingleNameBinding : BindingIdentifier
  1. 返回 true
SingleNameBinding : BindingIdentifier Initializer
  1. 返回 false
FormalParameters : [empty]
  1. 返回 true
FormalParameters : FunctionRestParameter
  1. 返回 false
FormalParameters : FormalParameterList , FunctionRestParameter
  1. 返回 false
FormalParameterList : FormalParameterList , FormalParameter
  1. 如果 FormalParameterListIsSimpleParameterListfalse,返回 false
  2. 返回 FormalParameterIsSimpleParameterList
FormalParameter : BindingElement
  1. 返回 BindingElementIsSimpleParameterList
ArrowParameters : BindingIdentifier
  1. 返回 true
ArrowParameters : CoverParenthesizedExpressionAndArrowParameterList
  1. formals 为被 CoverParenthesizedExpressionAndArrowParameterList 覆盖ArrowFormalParameters
  2. 返回 formalsIsSimpleParameterList
AsyncArrowBindingIdentifier : BindingIdentifier
  1. 返回 true
CoverCallExpressionAndAsyncArrowHead : MemberExpression Arguments
  1. head 为被 CoverCallExpressionAndAsyncArrowHead 覆盖AsyncArrowHead
  2. 返回 headIsSimpleParameterList

15.1.4 Static Semantics: HasInitializer

The syntax-directed operation HasInitializer takes no arguments and returns 一个布尔值. It is defined piecewise over the following productions:

BindingElement : BindingPattern
  1. 返回 false
BindingElement : BindingPattern Initializer
  1. 返回 true
SingleNameBinding : BindingIdentifier
  1. 返回 false
SingleNameBinding : BindingIdentifier Initializer
  1. 返回 true
FormalParameterList : FormalParameterList , FormalParameter
  1. 如果 FormalParameterListHasInitializertrue,返回 true
  2. 返回 FormalParameterHasInitializer

15.1.5 Static Semantics: ExpectedArgumentCount

The syntax-directed operation ExpectedArgumentCount takes no arguments and returns 一个非负整数. It is defined piecewise over the following productions:

FormalParameters : [empty] FunctionRestParameter
  1. 返回 0。
FormalParameters : FormalParameterList , FunctionRestParameter
  1. 返回 FormalParameterListExpectedArgumentCount
Note

FormalParameterList 的 ExpectedArgumentCount 是位于 rest 参数或第一个带有 Initializer 的 FormalParameter 左侧的 FormalParameters 的数量。允许在第一个带有初始化器的参数之后再出现没有初始化器的 FormalParameter,但此类参数被视为可选参数,其默认值为 undefined

FormalParameterList : FormalParameter
  1. 如果 FormalParameterHasInitializertrue,返回 0。
  2. 返回 1。
FormalParameterList : FormalParameterList , FormalParameter
  1. countFormalParameterListExpectedArgumentCount
  2. 如果 FormalParameterListHasInitializertrueFormalParameterHasInitializertrue,返回 count
  3. 返回 count + 1。
ArrowParameters : BindingIdentifier
  1. 返回 1。
ArrowParameters : CoverParenthesizedExpressionAndArrowParameterList
  1. formals 为被 CoverParenthesizedExpressionAndArrowParameterList 覆盖ArrowFormalParameters
  2. 返回 formalsExpectedArgumentCount
PropertySetParameterList : FormalParameter
  1. 如果 FormalParameterHasInitializertrue,返回 0。
  2. 返回 1。
AsyncArrowBindingIdentifier : BindingIdentifier
  1. 返回 1。

15.2 函数定义

语法

FunctionDeclaration[Yield, Await, Default] : function BindingIdentifier[?Yield, ?Await] ( FormalParameters[~Yield, ~Await] ) { FunctionBody[~Yield, ~Await] } [+Default] function ( FormalParameters[~Yield, ~Await] ) { FunctionBody[~Yield, ~Await] } FunctionExpression : function BindingIdentifier[~Yield, ~Await]opt ( FormalParameters[~Yield, ~Await] ) { FunctionBody[~Yield, ~Await] } FunctionBody[Yield, Await] : FunctionStatementList[?Yield, ?Await] FunctionStatementList[Yield, Await] : StatementList[?Yield, ?Await, +Return]opt

15.2.1 Static Semantics: 早期错误

FunctionDeclaration : function BindingIdentifier ( FormalParameters ) { FunctionBody } function ( FormalParameters ) { FunctionBody } FunctionExpression : function BindingIdentifieropt ( FormalParameters ) { FunctionBody } Note

FunctionBodyLexicallyDeclaredNames 不包含使用 var 或 function 声明绑定的标识符。

FunctionBody : FunctionStatementList

15.2.2 Static Semantics: FunctionBodyContainsUseStrict

The syntax-directed operation FunctionBodyContainsUseStrict takes no arguments and returns 布尔值. It is defined piecewise over the following productions:

FunctionBody : FunctionStatementList
  1. 如果 FunctionBody指令序言包含 Use Strict 指令,返回 true
  2. 返回 false

15.2.3 Runtime Semantics: EvaluateFunctionBody

The syntax-directed operation EvaluateFunctionBody takes arguments functionObject (ECMAScript 函数对象) and argumentsList (ECMAScript 语言值列表) and returns 返回补全或抛出补全. It is defined piecewise over the following productions:

FunctionBody : FunctionStatementList
  1. 执行 ? FunctionDeclarationInstantiation(functionObject, argumentsList)。
  2. 执行 FunctionStatementList 的 ? Evaluation
  3. 注:如果上一步产生了正常补全,则求值是通过越过 FunctionStatementList 的末尾而完成的。
  4. 返回 ReturnCompletion(undefined)。

15.2.4 Runtime Semantics: InstantiateOrdinaryFunctionObject

The syntax-directed operation InstantiateOrdinaryFunctionObject takes arguments env (Environment Record) and privateEnv (PrivateEnvironment Recordnull) and returns ECMAScript 函数对象. It is defined piecewise over the following productions:

FunctionDeclaration : function BindingIdentifier ( FormalParameters ) { FunctionBody }
  1. nameBindingIdentifierStringValue
  2. sourceTextFunctionDeclaration 匹配的源文本
  3. closureOrdinaryFunctionCreate(%Function.prototype%, sourceText, FormalParameters, FunctionBody, non-lexical-this, env, privateEnv)。
  4. 执行 SetFunctionName(closure, name)。
  5. 执行 MakeConstructor(closure)。
  6. 返回 closure
FunctionDeclaration : function ( FormalParameters ) { FunctionBody }
  1. sourceTextFunctionDeclaration 匹配的源文本
  2. closureOrdinaryFunctionCreate(%Function.prototype%, sourceText, FormalParameters, FunctionBody, non-lexical-this, env, privateEnv)。
  3. 执行 SetFunctionName(closure, "default")。
  4. 执行 MakeConstructor(closure)。
  5. 返回 closure
Note

匿名 FunctionDeclaration 只能作为 export default 声明的一部分出现,因此它的函数代码始终是严格模式代码

15.2.5 Runtime Semantics: InstantiateOrdinaryFunctionExpression

The syntax-directed operation InstantiateOrdinaryFunctionExpression takes optional argument name (属性键Private Name) and returns ECMAScript 函数对象. It is defined piecewise over the following productions:

FunctionExpression : function ( FormalParameters ) { FunctionBody }
  1. 如果 name 不存在,则将 name 设为空 String。
  2. env 为运行中的执行上下文的 LexicalEnvironment。
  3. privateEnv 为运行中的执行上下文的 PrivateEnvironment。
  4. sourceTextFunctionExpression 匹配的源文本
  5. closureOrdinaryFunctionCreate(%Function.prototype%, sourceText, FormalParameters, FunctionBody, non-lexical-this, env, privateEnv)。
  6. 执行 SetFunctionName(closure, name)。
  7. 执行 MakeConstructor(closure)。
  8. 返回 closure
FunctionExpression : function BindingIdentifier ( FormalParameters ) { FunctionBody }
  1. 断言:name 不存在。
  2. name 设为 BindingIdentifierStringValue
  3. outerEnv 为运行中的执行上下文的 LexicalEnvironment。
  4. funcEnvNewDeclarativeEnvironment(outerEnv)。
  5. 执行 ! funcEnv.CreateImmutableBinding(name, false)。
  6. privateEnv 为运行中的执行上下文的 PrivateEnvironment。
  7. sourceTextFunctionExpression 匹配的源文本
  8. closureOrdinaryFunctionCreate(%Function.prototype%, sourceText, FormalParameters, FunctionBody, non-lexical-this, funcEnv, privateEnv)。
  9. 执行 SetFunctionName(closure, name)。
  10. 执行 MakeConstructor(closure)。
  11. 执行 ! funcEnv.InitializeBinding(name, closure)。
  12. 返回 closure
Note

FunctionExpression 中的 BindingIdentifier 可以从 FunctionExpressionFunctionBody 内部引用,以允许函数递归调用自身。但是,与 FunctionDeclaration 不同,FunctionExpression 中的 BindingIdentifier 不能从包围该 FunctionExpression 的作用域中引用,也不会影响该作用域。

15.2.6 Runtime Semantics: Evaluation

FunctionDeclaration : function BindingIdentifier ( FormalParameters ) { FunctionBody }
  1. 返回 empty
Note 1 FunctionDeclaration : function ( FormalParameters ) { FunctionBody }
  1. 返回 empty
FunctionExpression : function BindingIdentifieropt ( FormalParameters ) { FunctionBody }
  1. 返回 FunctionExpressionInstantiateOrdinaryFunctionExpression
Note 2

对于每个使用 FunctionDeclarationFunctionExpression 定义的函数,都会自动创建一个 "prototype" 属性,以允许该函数可能被用作构造函数。

FunctionStatementList : [empty]
  1. 返回 undefined

15.3 箭头函数定义

语法

ArrowFunction[In, Yield, Await] : ArrowParameters[?Yield, ?Await] [no LineTerminator here] => ConciseBody[?In] ArrowParameters[Yield, Await] : BindingIdentifier[?Yield, ?Await] CoverParenthesizedExpressionAndArrowParameterList[?Yield, ?Await] ConciseBody[In] : [lookahead ≠ {] ExpressionBody[?In, ~Await] { FunctionBody[~Yield, ~Await] } ExpressionBody[In, Await] : AssignmentExpression[?In, ~Yield, ?Await]

补充语法

当处理产生式的一个实例
ArrowParameters[Yield, Await] : CoverParenthesizedExpressionAndArrowParameterList[?Yield, ?Await]
时,使用以下文法来细化对 CoverParenthesizedExpressionAndArrowParameterList 的解释:

ArrowFormalParameters[Yield, Await] : ( UniqueFormalParameters[?Yield, ?Await] )

15.3.1 Static Semantics: 早期错误

ArrowFunction : ArrowParameters => ConciseBody ArrowParameters : CoverParenthesizedExpressionAndArrowParameterList

15.3.2 Static Semantics: ConciseBodyContainsUseStrict

The syntax-directed operation ConciseBodyContainsUseStrict takes no arguments and returns 一个布尔值. It is defined piecewise over the following productions:

ConciseBody : ExpressionBody
  1. 返回 false
ConciseBody : { FunctionBody }
  1. 返回 FunctionBodyFunctionBodyContainsUseStrict

15.3.3 Runtime Semantics: EvaluateConciseBody

The syntax-directed operation EvaluateConciseBody takes arguments functionObject (一个 ECMAScript 函数对象) and argumentsList (ECMAScript 语言值List) and returns 一个返回完成或抛出完成. It is defined piecewise over the following productions:

ConciseBody : ExpressionBody
  1. 执行 ? FunctionDeclarationInstantiation(functionObject, argumentsList)。
  2. 返回 ? ExpressionBodyEvaluation

15.3.4 Runtime Semantics: InstantiateArrowFunctionExpression

The syntax-directed operation InstantiateArrowFunctionExpression takes optional argument name (一个属性键Private Name) and returns 一个 ECMAScript 函数对象. It is defined piecewise over the following productions:

ArrowFunction : ArrowParameters => ConciseBody
  1. 如果 name 不存在,则将 name 设为空 String。
  2. env 为运行中执行上下文的 LexicalEnvironment。
  3. privateEnv 为运行中执行上下文的 PrivateEnvironment。
  4. sourceTextArrowFunction匹配的源文本
  5. closureOrdinaryFunctionCreate(%Function.prototype%, sourceText, ArrowParameters, ConciseBody, lexical-this, env, privateEnv)。
  6. 执行 SetFunctionName(closure, name)。
  7. 返回 closure
Note

ArrowFunction 不会为 argumentssuperthisnew.target 定义局部绑定。ArrowFunction 内部对 argumentssuperthisnew.target 的任何引用都必须解析到词法外围环境中的绑定。通常这会是紧邻外围函数的 Function Environment。即使 ArrowFunction 可以包含对 super 的引用,在步骤 5 中创建的函数对象也不会通过执行 MakeMethod 而成为方法。引用 superArrowFunction 总是包含在非 ArrowFunction 内,实现 super 所需的状态可通过 ArrowFunction函数对象所捕获的 env 访问。

15.3.5 Runtime Semantics: Evaluation

ArrowFunction : ArrowParameters => ConciseBody
  1. 返回 ArrowFunctionInstantiateArrowFunctionExpression
ExpressionBody : AssignmentExpression
  1. exprRef 为 ? AssignmentExpressionEvaluation
  2. exprValue 为 ? GetValue(exprRef)。
  3. 返回 ReturnCompletion(exprValue)。

15.4 方法定义

语法

MethodDefinition[Yield, Await] : ClassElementName[?Yield, ?Await] ( UniqueFormalParameters[~Yield, ~Await] ) { FunctionBody[~Yield, ~Await] } GeneratorMethod[?Yield, ?Await] AsyncMethod[?Yield, ?Await] AsyncGeneratorMethod[?Yield, ?Await] get ClassElementName[?Yield, ?Await] ( ) { FunctionBody[~Yield, ~Await] } set ClassElementName[?Yield, ?Await] ( PropertySetParameterList ) { FunctionBody[~Yield, ~Await] } PropertySetParameterList : FormalParameter[~Yield, ~Await]

15.4.1 Static Semantics: 早期错误

MethodDefinition : ClassElementName ( UniqueFormalParameters ) { FunctionBody } MethodDefinition : set ClassElementName ( PropertySetParameterList ) { FunctionBody }

15.4.2 Static Semantics: HasDirectSuper

The syntax-directed operation HasDirectSuper takes no arguments and returns 一个布尔值. It is defined piecewise over the following productions:

MethodDefinition : ClassElementName ( UniqueFormalParameters ) { FunctionBody }
  1. 如果 UniqueFormalParameters Contains SuperCalltrue,返回 true
  2. 返回 FunctionBody Contains SuperCall
MethodDefinition : get ClassElementName ( ) { FunctionBody }
  1. 返回 FunctionBody Contains SuperCall
MethodDefinition : set ClassElementName ( PropertySetParameterList ) { FunctionBody }
  1. 如果 PropertySetParameterList Contains SuperCalltrue,返回 true
  2. 返回 FunctionBody Contains SuperCall
GeneratorMethod : * ClassElementName ( UniqueFormalParameters ) { GeneratorBody }
  1. 如果 UniqueFormalParameters Contains SuperCalltrue,返回 true
  2. 返回 GeneratorBody Contains SuperCall
AsyncGeneratorMethod : async * ClassElementName ( UniqueFormalParameters ) { AsyncGeneratorBody }
  1. 如果 UniqueFormalParameters Contains SuperCalltrue,返回 true
  2. 返回 AsyncGeneratorBody Contains SuperCall
AsyncMethod : async ClassElementName ( UniqueFormalParameters ) { AsyncFunctionBody }
  1. 如果 UniqueFormalParameters Contains SuperCalltrue,返回 true
  2. 返回 AsyncFunctionBody Contains SuperCall

15.4.3 Static Semantics: SpecialMethod

The syntax-directed operation SpecialMethod takes no arguments and returns 一个布尔值. It is defined piecewise over the following productions:

MethodDefinition : ClassElementName ( UniqueFormalParameters ) { FunctionBody }
  1. 返回 false
MethodDefinition : GeneratorMethod AsyncMethod AsyncGeneratorMethod get ClassElementName ( ) { FunctionBody } set ClassElementName ( PropertySetParameterList ) { FunctionBody }
  1. 返回 true

15.4.4 Runtime Semantics: DefineMethod

The syntax-directed operation DefineMethod takes argument object (一个 Object) and optional argument functionPrototype (一个 Object) and returns 要么是一个正常完成,其中包含带有字段 [[Key]](一个属性键)和 [[Closure]](一个 ECMAScript 函数对象)的 Record;要么是一个突然完成. It is defined piecewise over the following productions:

MethodDefinition : ClassElementName ( UniqueFormalParameters ) { FunctionBody }
  1. propertyKey 为 ? ClassElementNameEvaluation
  2. env 为运行中执行上下文的 LexicalEnvironment。
  3. privateEnv 为运行中执行上下文的 PrivateEnvironment。
  4. 如果 functionPrototype 存在,则
    1. prototypefunctionPrototype
  5. 否则,
    1. prototype%Function.prototype%
  6. sourceTextMethodDefinition匹配的源文本
  7. closureOrdinaryFunctionCreate(prototype, sourceText, UniqueFormalParameters, FunctionBody, non-lexical-this, env, privateEnv)。
  8. 执行 MakeMethod(closure, object)。
  9. 返回 Record { [[Key]]: propertyKey, [[Closure]]: closure }。

15.4.5 Runtime Semantics: MethodDefinitionEvaluation

The syntax-directed operation MethodDefinitionEvaluation takes arguments object (一个 Object) and enumerable (一个布尔值) and returns 要么是一个正常完成,其中包含一个 PrivateElementunused;要么是一个突然完成. It is defined piecewise over the following productions:

MethodDefinition : ClassElementName ( UniqueFormalParameters ) { FunctionBody }
  1. methodDef 为以 object 为参数的 MethodDefinition 的 ? DefineMethod
  2. 执行 SetFunctionName(methodDef.[[Closure]], methodDef.[[Key]])。
  3. 返回 ? DefineMethodProperty(object, methodDef.[[Key]], methodDef.[[Closure]], enumerable)。
MethodDefinition : get ClassElementName ( ) { FunctionBody }
  1. propertyKey 为 ? ClassElementNameEvaluation
  2. env 为运行中执行上下文的 LexicalEnvironment。
  3. privateEnv 为运行中执行上下文的 PrivateEnvironment。
  4. sourceTextMethodDefinition匹配的源文本
  5. formalParameterList 为产生式 FormalParameters : [empty] 的一个实例。
  6. closureOrdinaryFunctionCreate(%Function.prototype%, sourceText, formalParameterList, FunctionBody, non-lexical-this, env, privateEnv)。
  7. 执行 MakeMethod(closure, object)。
  8. 执行 SetFunctionName(closure, propertyKey, "get")。
  9. 如果 propertyKeyPrivate Name,则
    1. 返回 PrivateElement { [[Key]]: propertyKey, [[Kind]]: accessor, [[Get]]: closure, [[Set]]: undefined }。
  10. desc 为 PropertyDescriptor { [[Get]]: closure, [[Enumerable]]: enumerable, [[Configurable]]: true }。
  11. 执行 ? DefinePropertyOrThrow(object, propertyKey, desc)。
  12. 返回 unused
MethodDefinition : set ClassElementName ( PropertySetParameterList ) { FunctionBody }
  1. propertyKey 为 ? ClassElementNameEvaluation
  2. env 为运行中执行上下文的 LexicalEnvironment。
  3. privateEnv 为运行中执行上下文的 PrivateEnvironment。
  4. sourceTextMethodDefinition匹配的源文本
  5. closureOrdinaryFunctionCreate(%Function.prototype%, sourceText, PropertySetParameterList, FunctionBody, non-lexical-this, env, privateEnv)。
  6. 执行 MakeMethod(closure, object)。
  7. 执行 SetFunctionName(closure, propertyKey, "set")。
  8. 如果 propertyKeyPrivate Name,则
    1. 返回 PrivateElement { [[Key]]: propertyKey, [[Kind]]: accessor, [[Get]]: undefined, [[Set]]: closure }。
  9. desc 为 PropertyDescriptor { [[Set]]: closure, [[Enumerable]]: enumerable, [[Configurable]]: true }。
  10. 执行 ? DefinePropertyOrThrow(object, propertyKey, desc)。
  11. 返回 unused
GeneratorMethod : * ClassElementName ( UniqueFormalParameters ) { GeneratorBody }
  1. propertyKey 为 ? ClassElementNameEvaluation
  2. env 为运行中执行上下文的 LexicalEnvironment。
  3. privateEnv 为运行中执行上下文的 PrivateEnvironment。
  4. sourceTextGeneratorMethod匹配的源文本
  5. closureOrdinaryFunctionCreate(%GeneratorFunction.prototype%, sourceText, UniqueFormalParameters, GeneratorBody, non-lexical-this, env, privateEnv)。
  6. 执行 MakeMethod(closure, object)。
  7. 执行 SetFunctionName(closure, propertyKey)。
  8. prototypeOrdinaryObjectCreate(%GeneratorPrototype%)。
  9. 执行 ! DefinePropertyOrThrow(closure, "prototype", PropertyDescriptor { [[Value]]: prototype, [[Writable]]: true, [[Enumerable]]: false, [[Configurable]]: false })。
  10. 返回 ? DefineMethodProperty(object, propertyKey, closure, enumerable)。
AsyncGeneratorMethod : async * ClassElementName ( UniqueFormalParameters ) { AsyncGeneratorBody }
  1. propertyKey 为 ? ClassElementNameEvaluation
  2. env 为运行中执行上下文的 LexicalEnvironment。
  3. privateEnv 为运行中执行上下文的 PrivateEnvironment。
  4. sourceTextAsyncGeneratorMethod匹配的源文本
  5. closureOrdinaryFunctionCreate(%AsyncGeneratorFunction.prototype%, sourceText, UniqueFormalParameters, AsyncGeneratorBody, non-lexical-this, env, privateEnv)。
  6. 执行 MakeMethod(closure, object)。
  7. 执行 SetFunctionName(closure, propertyKey)。
  8. prototypeOrdinaryObjectCreate(%AsyncGeneratorPrototype%)。
  9. 执行 ! DefinePropertyOrThrow(closure, "prototype", PropertyDescriptor { [[Value]]: prototype, [[Writable]]: true, [[Enumerable]]: false, [[Configurable]]: false })。
  10. 返回 ? DefineMethodProperty(object, propertyKey, closure, enumerable)。
AsyncMethod : async ClassElementName ( UniqueFormalParameters ) { AsyncFunctionBody }
  1. propertyKey 为 ? ClassElementNameEvaluation
  2. env 为运行中执行上下文的 LexicalEnvironment。
  3. privateEnv 为运行中执行上下文的 PrivateEnvironment。
  4. sourceTextAsyncMethod匹配的源文本
  5. closureOrdinaryFunctionCreate(%AsyncFunction.prototype%, sourceText, UniqueFormalParameters, AsyncFunctionBody, non-lexical-this, env, privateEnv)。
  6. 执行 MakeMethod(closure, object)。
  7. 执行 SetFunctionName(closure, propertyKey)。
  8. 返回 ? DefineMethodProperty(object, propertyKey, closure, enumerable)。

15.5 生成器函数定义

语法

GeneratorDeclaration[Yield, Await, Default] : function * BindingIdentifier[?Yield, ?Await] ( FormalParameters[+Yield, ~Await] ) { GeneratorBody } [+Default] function * ( FormalParameters[+Yield, ~Await] ) { GeneratorBody } GeneratorExpression : function * BindingIdentifier[+Yield, ~Await]opt ( FormalParameters[+Yield, ~Await] ) { GeneratorBody } GeneratorMethod[Yield, Await] : * ClassElementName[?Yield, ?Await] ( UniqueFormalParameters[+Yield, ~Await] ) { GeneratorBody } GeneratorBody : FunctionBody[+Yield, ~Await] YieldExpression[In, Await] : yield yield [no LineTerminator here] AssignmentExpression[?In, +Yield, ?Await] yield [no LineTerminator here] * AssignmentExpression[?In, +Yield, ?Await] Note 1

紧跟在 yield 之后的语法上下文要求使用 InputElementRegExpOrTemplateTail 词法目标。

Note 2

YieldExpression 不能在生成器函数的 FormalParameters 内使用,因为作为 FormalParameters 一部分的任何表达式都会在生成的 Generator 进入可恢复状态之前求值。

Note 3

与 Generator 相关的抽象操作定义于 27.5.3

15.5.1 Static Semantics: 早期错误

GeneratorMethod : * ClassElementName ( UniqueFormalParameters ) { GeneratorBody } GeneratorDeclaration : function * BindingIdentifier ( FormalParameters ) { GeneratorBody } function * ( FormalParameters ) { GeneratorBody } GeneratorExpression : function * BindingIdentifieropt ( FormalParameters ) { GeneratorBody }

15.5.2 Runtime Semantics: EvaluateGeneratorBody

The syntax-directed operation EvaluateGeneratorBody takes arguments functionObject (一个 ECMAScript 函数对象) and argumentsList (ECMAScript 语言值List) and returns 一个抛出完成或返回完成. It is defined piecewise over the following productions:

GeneratorBody : FunctionBody
  1. 执行 ? FunctionDeclarationInstantiation(functionObject, argumentsList)。
  2. generator 为 ? OrdinaryCreateFromConstructor(functionObject, "%GeneratorPrototype%", « [[GeneratorState]], [[GeneratorContext]], [[GeneratorBrand]] »)。
  3. generator.[[GeneratorBrand]] 设为 empty
  4. generator.[[GeneratorState]] 设为 suspended-start
  5. 执行 GeneratorStart(generator, FunctionBody)。
  6. 返回 ReturnCompletion(generator)。

15.5.3 Runtime Semantics: InstantiateGeneratorFunctionObject

The syntax-directed operation InstantiateGeneratorFunctionObject takes arguments env (一个 Environment Record) and privateEnv (一个 PrivateEnvironment Recordnull) and returns 一个 ECMAScript 函数对象. It is defined piecewise over the following productions:

GeneratorDeclaration : function * BindingIdentifier ( FormalParameters ) { GeneratorBody }
  1. nameBindingIdentifierStringValue
  2. sourceTextGeneratorDeclaration匹配的源文本
  3. closureOrdinaryFunctionCreate(%GeneratorFunction.prototype%, sourceText, FormalParameters, GeneratorBody, non-lexical-this, env, privateEnv)。
  4. 执行 SetFunctionName(closure, name)。
  5. prototypeOrdinaryObjectCreate(%GeneratorPrototype%)。
  6. 执行 ! DefinePropertyOrThrow(closure, "prototype", PropertyDescriptor { [[Value]]: prototype, [[Writable]]: true, [[Enumerable]]: false, [[Configurable]]: false })。
  7. 返回 closure
GeneratorDeclaration : function * ( FormalParameters ) { GeneratorBody }
  1. sourceTextGeneratorDeclaration匹配的源文本
  2. closureOrdinaryFunctionCreate(%GeneratorFunction.prototype%, sourceText, FormalParameters, GeneratorBody, non-lexical-this, env, privateEnv)。
  3. 执行 SetFunctionName(closure, "default")。
  4. prototypeOrdinaryObjectCreate(%GeneratorPrototype%)。
  5. 执行 ! DefinePropertyOrThrow(closure, "prototype", PropertyDescriptor { [[Value]]: prototype, [[Writable]]: true, [[Enumerable]]: false, [[Configurable]]: false })。
  6. 返回 closure
Note

匿名 GeneratorDeclaration 只能作为 export default 声明的一部分出现,因此其函数代码总是严格模式代码

15.5.4 Runtime Semantics: InstantiateGeneratorFunctionExpression

The syntax-directed operation InstantiateGeneratorFunctionExpression takes optional argument name (一个属性键Private Name) and returns 一个 ECMAScript 函数对象. It is defined piecewise over the following productions:

GeneratorExpression : function * ( FormalParameters ) { GeneratorBody }
  1. 如果 name 不存在,则将 name 设为空 String。
  2. env 为运行中执行上下文的 LexicalEnvironment。
  3. privateEnv 为运行中执行上下文的 PrivateEnvironment。
  4. sourceTextGeneratorExpression匹配的源文本
  5. closureOrdinaryFunctionCreate(%GeneratorFunction.prototype%, sourceText, FormalParameters, GeneratorBody, non-lexical-this, env, privateEnv)。
  6. 执行 SetFunctionName(closure, name)。
  7. prototypeOrdinaryObjectCreate(%GeneratorPrototype%)。
  8. 执行 ! DefinePropertyOrThrow(closure, "prototype", PropertyDescriptor { [[Value]]: prototype, [[Writable]]: true, [[Enumerable]]: false, [[Configurable]]: false })。
  9. 返回 closure
GeneratorExpression : function * BindingIdentifier ( FormalParameters ) { GeneratorBody }
  1. 断言:name 不存在。
  2. name 设为 BindingIdentifierStringValue
  3. outerEnv 为运行中执行上下文的 LexicalEnvironment。
  4. funcEnvNewDeclarativeEnvironment(outerEnv)。
  5. 执行 ! funcEnv.CreateImmutableBinding(name, false)。
  6. privateEnv 为运行中执行上下文的 PrivateEnvironment。
  7. sourceTextGeneratorExpression匹配的源文本
  8. closureOrdinaryFunctionCreate(%GeneratorFunction.prototype%, sourceText, FormalParameters, GeneratorBody, non-lexical-this, funcEnv, privateEnv)。
  9. 执行 SetFunctionName(closure, name)。
  10. prototypeOrdinaryObjectCreate(%GeneratorPrototype%)。
  11. 执行 ! DefinePropertyOrThrow(closure, "prototype", PropertyDescriptor { [[Value]]: prototype, [[Writable]]: true, [[Enumerable]]: false, [[Configurable]]: false })。
  12. 执行 ! funcEnv.InitializeBinding(name, closure)。
  13. 返回 closure
Note

GeneratorExpression 中的 BindingIdentifier 可在 GeneratorExpressionFunctionBody 内被引用,以允许生成器代码递归调用自身。然而,与 GeneratorDeclaration 中不同,GeneratorExpression 中的 BindingIdentifier 不能从外围作用域引用,也不会影响包围 GeneratorExpression 的作用域。

15.5.5 Runtime Semantics: Evaluation

GeneratorExpression : function * BindingIdentifieropt ( FormalParameters ) { GeneratorBody }
  1. 返回 GeneratorExpressionInstantiateGeneratorFunctionExpression
YieldExpression : yield
  1. 返回 ? Yield(undefined)。
YieldExpression : yield AssignmentExpression
  1. exprRef 为 ? AssignmentExpressionEvaluation
  2. value 为 ? GetValue(exprRef)。
  3. 返回 ? Yield(value)。
YieldExpression : yield * AssignmentExpression
  1. generatorKindGetGeneratorKind()。
  2. 断言:generatorKindsyncasync
  3. exprRef 为 ? AssignmentExpressionEvaluation
  4. value 为 ? GetValue(exprRef)。
  5. iteratorRecord 为 ? GetIterator(value, generatorKind)。
  6. iteratoriteratorRecord.[[Iterator]]
  7. receivedNormalCompletion(undefined)。
  8. 重复,
    1. 如果 received正常完成,则
      1. innerResult 为 ? Call(iteratorRecord.[[NextMethod]], iteratorRecord.[[Iterator]], « received.[[Value]] »)。
      2. 如果 generatorKindasync,则将 innerResult 设为 ? Await(innerResult)。
      3. 如果 innerResult 不是 Object,则抛出 TypeError 异常。
      4. done 为 ? IteratorComplete(innerResult)。
      5. 如果 donetrue,则
        1. 返回 ? IteratorValue(innerResult)。
      6. 如果 generatorKindasync,则将 received 设为 Completion(AsyncGeneratorYield(? IteratorValue(innerResult)))。
      7. 否则,将 received 设为 Completion(GeneratorYield(innerResult))。
    2. 否则如果 received 是抛出完成,则
      1. throw 为 ? GetMethod(iterator, "throw")。
      2. 如果 throw 不是 undefined,则
        1. innerResult 为 ? Call(throw, iterator, « received.[[Value]] »)。
        2. 如果 generatorKindasync,则将 innerResult 设为 ? Await(innerResult)。
        3. 注:来自内部迭代器 throw 方法的异常会被传播。来自内部 throw 方法的正常完成会以类似于内部 next 的方式处理。
        4. 如果 innerResult 不是 Object,则抛出 TypeError 异常。
        5. done 为 ? IteratorComplete(innerResult)。
        6. 如果 donetrue,则
          1. 返回 ? IteratorValue(innerResult)。
        7. 如果 generatorKindasync,则将 received 设为 Completion(AsyncGeneratorYield(? IteratorValue(innerResult)))。
        8. 否则,将 received 设为 Completion(GeneratorYield(innerResult))。
      3. 否则,
        1. 注:如果 iterator 没有 throw 方法,此抛出将终止 yield* 循环。但首先需要给 iterator 一个清理的机会。
        2. closeCompletionNormalCompletion(empty)。
        3. 如果 generatorKindasync,执行 ? AsyncIteratorClose(iteratorRecord, closeCompletion)。
        4. 否则,执行 ? IteratorClose(iteratorRecord, closeCompletion)。
        5. 注:下一步抛出 TypeError,用于表明存在 yield* 协议违例:iterator 没有 throw 方法。
        6. 抛出 TypeError 异常。
    3. 否则,
      1. 断言:received 是返回完成。
      2. return 为 ? GetMethod(iterator, "return")。
      3. 如果 returnundefined,则
        1. receivedValuereceived.[[Value]]
        2. 如果 generatorKindasync,则
          1. receivedValue 设为 ? Await(receivedValue)。
        3. 返回 ReturnCompletion(receivedValue)。
      4. innerReturnResult 为 ? Call(return, iterator, « received.[[Value]] »)。
      5. 如果 generatorKindasync,则将 innerReturnResult 设为 ? Await(innerReturnResult)。
      6. 如果 innerReturnResult 不是 Object,则抛出 TypeError 异常。
      7. done 为 ? IteratorComplete(innerReturnResult)。
      8. 如果 donetrue,则
        1. returnedValue 为 ? IteratorValue(innerReturnResult)。
        2. 返回 ReturnCompletion(returnedValue)。
      9. 如果 generatorKindasync,则将 received 设为 Completion(AsyncGeneratorYield(? IteratorValue(innerReturnResult)))。
      10. 否则,将 received 设为 Completion(GeneratorYield(innerReturnResult))。

15.6 异步生成器函数定义

语法

AsyncGeneratorDeclaration[Yield, Await, Default] : async [no LineTerminator here] function * BindingIdentifier[?Yield, ?Await] ( FormalParameters[+Yield, +Await] ) { AsyncGeneratorBody } [+Default] async [no LineTerminator here] function * ( FormalParameters[+Yield, +Await] ) { AsyncGeneratorBody } AsyncGeneratorExpression : async [no LineTerminator here] function * BindingIdentifier[+Yield, +Await]opt ( FormalParameters[+Yield, +Await] ) { AsyncGeneratorBody } AsyncGeneratorMethod[Yield, Await] : async [no LineTerminator here] * ClassElementName[?Yield, ?Await] ( UniqueFormalParameters[+Yield, +Await] ) { AsyncGeneratorBody } AsyncGeneratorBody : FunctionBody[+Yield, +Await] Note 1

YieldExpressionAwaitExpression 不能在异步生成器函数的 FormalParameters 内使用,因为作为 FormalParameters 一部分的任何表达式都会在生成的 AsyncGenerator 进入可恢复状态之前求值。

Note 2

与 AsyncGenerator 相关的抽象操作定义于 27.6.3

15.6.1 Static Semantics: 早期错误

AsyncGeneratorMethod : async * ClassElementName ( UniqueFormalParameters ) { AsyncGeneratorBody } AsyncGeneratorDeclaration : async function * BindingIdentifier ( FormalParameters ) { AsyncGeneratorBody } async function * ( FormalParameters ) { AsyncGeneratorBody } AsyncGeneratorExpression : async function * BindingIdentifieropt ( FormalParameters ) { AsyncGeneratorBody }

15.6.2 Runtime Semantics: EvaluateAsyncGeneratorBody

The syntax-directed operation EvaluateAsyncGeneratorBody takes arguments functionObject (一个 ECMAScript 函数对象) and argumentsList (ECMAScript 语言值List) and returns 一个抛出完成或返回完成. It is defined piecewise over the following productions:

AsyncGeneratorBody : FunctionBody
  1. 执行 ? FunctionDeclarationInstantiation(functionObject, argumentsList)。
  2. generator 为 ? OrdinaryCreateFromConstructor(functionObject, "%AsyncGeneratorPrototype%", « [[AsyncGeneratorState]], [[AsyncGeneratorContext]], [[AsyncGeneratorQueue]], [[GeneratorBrand]] »)。
  3. generator.[[GeneratorBrand]] 设为 empty
  4. generator.[[AsyncGeneratorState]] 设为 suspended-start
  5. 执行 AsyncGeneratorStart(generator, FunctionBody)。
  6. 返回 ReturnCompletion(generator)。

15.6.3 Runtime Semantics: InstantiateAsyncGeneratorFunctionObject

The syntax-directed operation InstantiateAsyncGeneratorFunctionObject takes arguments env (一个 Environment Record) and privateEnv (一个 PrivateEnvironment Recordnull) and returns 一个 ECMAScript 函数对象. It is defined piecewise over the following productions:

AsyncGeneratorDeclaration : async function * BindingIdentifier ( FormalParameters ) { AsyncGeneratorBody }
  1. nameBindingIdentifierStringValue
  2. sourceTextAsyncGeneratorDeclaration匹配的源文本
  3. closureOrdinaryFunctionCreate(%AsyncGeneratorFunction.prototype%, sourceText, FormalParameters, AsyncGeneratorBody, non-lexical-this, env, privateEnv)。
  4. 执行 SetFunctionName(closure, name)。
  5. prototypeOrdinaryObjectCreate(%AsyncGeneratorPrototype%)。
  6. 执行 ! DefinePropertyOrThrow(closure, "prototype", PropertyDescriptor { [[Value]]: prototype, [[Writable]]: true, [[Enumerable]]: false, [[Configurable]]: false })。
  7. 返回 closure
AsyncGeneratorDeclaration : async function * ( FormalParameters ) { AsyncGeneratorBody }
  1. sourceTextAsyncGeneratorDeclaration匹配的源文本
  2. closureOrdinaryFunctionCreate(%AsyncGeneratorFunction.prototype%, sourceText, FormalParameters, AsyncGeneratorBody, non-lexical-this, env, privateEnv)。
  3. 执行 SetFunctionName(closure, "default")。
  4. prototypeOrdinaryObjectCreate(%AsyncGeneratorPrototype%)。
  5. 执行 ! DefinePropertyOrThrow(closure, "prototype", PropertyDescriptor { [[Value]]: prototype, [[Writable]]: true, [[Enumerable]]: false, [[Configurable]]: false })。
  6. 返回 closure
Note

匿名 AsyncGeneratorDeclaration 只能作为 export default 声明的一部分出现。

15.6.4 Runtime Semantics: InstantiateAsyncGeneratorFunctionExpression

The syntax-directed operation InstantiateAsyncGeneratorFunctionExpression takes optional argument name (一个属性键Private Name) and returns 一个 ECMAScript 函数对象. It is defined piecewise over the following productions:

AsyncGeneratorExpression : async function * ( FormalParameters ) { AsyncGeneratorBody }
  1. 如果 name 不存在,则将 name 设为空 String。
  2. env 为运行中执行上下文的 LexicalEnvironment。
  3. privateEnv 为运行中执行上下文的 PrivateEnvironment。
  4. sourceTextAsyncGeneratorExpression匹配的源文本
  5. closureOrdinaryFunctionCreate(%AsyncGeneratorFunction.prototype%, sourceText, FormalParameters, AsyncGeneratorBody, non-lexical-this, env, privateEnv)。
  6. 执行 SetFunctionName(closure, name)。
  7. prototypeOrdinaryObjectCreate(%AsyncGeneratorPrototype%)。
  8. 执行 ! DefinePropertyOrThrow(closure, "prototype", PropertyDescriptor { [[Value]]: prototype, [[Writable]]: true, [[Enumerable]]: false, [[Configurable]]: false })。
  9. 返回 closure
AsyncGeneratorExpression : async function * BindingIdentifier ( FormalParameters ) { AsyncGeneratorBody }
  1. 断言:name 不存在。
  2. name 设为 BindingIdentifierStringValue
  3. outerEnv 为运行中执行上下文的 LexicalEnvironment。
  4. funcEnvNewDeclarativeEnvironment(outerEnv)。
  5. 执行 ! funcEnv.CreateImmutableBinding(name, false)。
  6. privateEnv 为运行中执行上下文的 PrivateEnvironment。
  7. sourceTextAsyncGeneratorExpression匹配的源文本
  8. closureOrdinaryFunctionCreate(%AsyncGeneratorFunction.prototype%, sourceText, FormalParameters, AsyncGeneratorBody, non-lexical-this, funcEnv, privateEnv)。
  9. 执行 SetFunctionName(closure, name)。
  10. prototypeOrdinaryObjectCreate(%AsyncGeneratorPrototype%)。
  11. 执行 ! DefinePropertyOrThrow(closure, "prototype", PropertyDescriptor { [[Value]]: prototype, [[Writable]]: true, [[Enumerable]]: false, [[Configurable]]: false })。
  12. 执行 ! funcEnv.InitializeBinding(name, closure)。
  13. 返回 closure
Note

AsyncGeneratorExpression 中的 BindingIdentifier 可在 AsyncGeneratorExpressionAsyncGeneratorBody 内被引用,以允许生成器代码递归调用自身。然而,与 AsyncGeneratorDeclaration 中不同,AsyncGeneratorExpression 中的 BindingIdentifier 不能从外围作用域引用,也不会影响包围 AsyncGeneratorExpression 的作用域。

15.6.5 Runtime Semantics: Evaluation

AsyncGeneratorExpression : async function * BindingIdentifieropt ( FormalParameters ) { AsyncGeneratorBody }
  1. 返回 AsyncGeneratorExpressionInstantiateAsyncGeneratorFunctionExpression

15.7 类定义

语法

ClassDeclaration[Yield, Await, Default] : class BindingIdentifier[?Yield, ?Await] ClassTail[?Yield, ?Await] [+Default] class ClassTail[?Yield, ?Await] ClassExpression[Yield, Await] : class BindingIdentifier[?Yield, ?Await]opt ClassTail[?Yield, ?Await] ClassTail[Yield, Await] : ClassHeritage[?Yield, ?Await]opt { ClassBody[?Yield, ?Await]opt } ClassHeritage[Yield, Await] : extends LeftHandSideExpression[?Yield, ?Await] ClassBody[Yield, Await] : ClassElementList[?Yield, ?Await] ClassElementList[Yield, Await] : ClassElement[?Yield, ?Await] ClassElementList[?Yield, ?Await] ClassElement[?Yield, ?Await] ClassElement[Yield, Await] : MethodDefinition[?Yield, ?Await] static MethodDefinition[?Yield, ?Await] FieldDefinition[?Yield, ?Await] ; static FieldDefinition[?Yield, ?Await] ; ClassStaticBlock ; FieldDefinition[Yield, Await] : ClassElementName[?Yield, ?Await] Initializer[+In, ?Yield, ?Await]opt ClassElementName[Yield, Await] : PropertyName[?Yield, ?Await] PrivateIdentifier ClassStaticBlock : static { ClassStaticBlockBody } ClassStaticBlockBody : ClassStaticBlockStatementList ClassStaticBlockStatementList : StatementList[~Yield, +Await, ~Return]opt Note

类定义始终是严格模式代码

15.7.1 Static Semantics: 早期错误

ClassTail : ClassHeritageopt { ClassBody } ClassBody : ClassElementList ClassElement : MethodDefinition ClassElement : static MethodDefinition ClassElement : FieldDefinition ; ClassElement : static FieldDefinition ; FieldDefinition : ClassElementName Initializeropt ClassElementName : PrivateIdentifier ClassStaticBlockBody : ClassStaticBlockStatementList

15.7.2 Static Semantics: ClassElementKind

The syntax-directed operation ClassElementKind takes no arguments and returns constructor-methodnon-constructor-methodempty. It is defined piecewise over the following productions:

ClassElement : MethodDefinition
  1. 如果 MethodDefinitionPropName"constructor",返回 constructor-method
  2. 返回 non-constructor-method
ClassElement : static MethodDefinition FieldDefinition ; static FieldDefinition ;
  1. 返回 non-constructor-method
ClassElement : ClassStaticBlock
  1. 返回 non-constructor-method
ClassElement : ;
  1. 返回 empty

15.7.3 Static Semantics: ConstructorMethod

The syntax-directed operation ConstructorMethod takes no arguments and returns 一个 ClassElement 解析节点empty. It is defined piecewise over the following productions:

ClassElementList : ClassElement
  1. 如果 ClassElementClassElementKindconstructor-method,返回 ClassElement
  2. 返回 empty
ClassElementList : ClassElementList ClassElement
  1. headClassElementListConstructorMethod
  2. 如果 head 不是 empty,返回 head
  3. 如果 ClassElementClassElementKindconstructor-method,返回 ClassElement
  4. 返回 empty
Note

早期错误规则确保只有一个名为 "constructor" 的方法定义,并且它不是访问器属性或生成器定义。

15.7.4 Static Semantics: IsStatic

The syntax-directed operation IsStatic takes no arguments and returns 一个布尔值. It is defined piecewise over the following productions:

ClassElement : MethodDefinition
  1. 返回 false
ClassElement : static MethodDefinition
  1. 返回 true
ClassElement : FieldDefinition ;
  1. 返回 false
ClassElement : static FieldDefinition ;
  1. 返回 true
ClassElement : ClassStaticBlock
  1. 返回 true
ClassElement : ;
  1. 返回 false

15.7.5 Static Semantics: NonConstructorElements

The syntax-directed operation NonConstructorElements takes no arguments and returns 一个 ClassElement 解析节点List. It is defined piecewise over the following productions:

ClassElementList : ClassElement
  1. 如果 ClassElementClassElementKindnon-constructor-method,则
    1. 返回 « ClassElement »。
  2. 返回一个新的空 List
ClassElementList : ClassElementList ClassElement
  1. listClassElementListNonConstructorElements
  2. 如果 ClassElementClassElementKindnon-constructor-method,则
    1. ClassElement 追加到 list
  3. 返回 list

15.7.6 Static Semantics: PrototypePropertyNameList

The syntax-directed operation PrototypePropertyNameList takes no arguments and returns 一个属性键List. It is defined piecewise over the following productions:

ClassElementList : ClassElement
  1. propNameClassElementPropName
  2. 如果 propNameempty,返回一个新的空 List
  3. 如果 ClassElementIsStatictrue,返回一个新的空 List
  4. 返回 « propName »。
ClassElementList : ClassElementList ClassElement
  1. listClassElementListPrototypePropertyNameList
  2. propNameClassElementPropName
  3. 如果 propNameempty,返回 list
  4. 如果 ClassElementIsStatictrue,返回 list
  5. 返回 list 与 « propName » 的列表拼接。

15.7.7 Static Semantics: AllPrivateIdentifiersValid

The syntax-directed operation AllPrivateIdentifiersValid takes argument names (一个字符串的 List) and returns 一个布尔值.

本规范中未列在下面的每个文法产生式替代项,都隐式具有以下 AllPrivateIdentifiersValid 默认定义:

  1. 对此解析节点的每个子节点 child,执行
    1. 如果 child 是非终结符的一个实例,则
      1. 如果以参数 names 调用 childAllPrivateIdentifiersValidfalse,返回 false
  2. 返回 true
MemberExpression : MemberExpression . PrivateIdentifier
  1. 如果 names 包含 PrivateIdentifierStringValue,则
    1. 返回以参数 names 调用 MemberExpressionAllPrivateIdentifiersValid
  2. 返回 false
CallExpression : CallExpression . PrivateIdentifier
  1. 如果 names 包含 PrivateIdentifierStringValue,则
    1. 返回以参数 names 调用 CallExpressionAllPrivateIdentifiersValid
  2. 返回 false
OptionalChain : ?. PrivateIdentifier
  1. 如果 names 包含 PrivateIdentifierStringValue,返回 true
  2. 返回 false
OptionalChain : OptionalChain . PrivateIdentifier
  1. 如果 names 包含 PrivateIdentifierStringValue,则
    1. 返回以参数 names 调用 OptionalChainAllPrivateIdentifiersValid
  2. 返回 false
ClassBody : ClassElementList
  1. newNamesnamesClassBodyPrivateBoundIdentifiers 的列表拼接。
  2. 返回以参数 newNames 调用 ClassElementListAllPrivateIdentifiersValid
RelationalExpression : PrivateIdentifier in ShiftExpression
  1. 如果 names 包含 PrivateIdentifierStringValue,则
    1. 返回以参数 names 调用 ShiftExpressionAllPrivateIdentifiersValid
  2. 返回 false

15.7.8 Static Semantics: PrivateBoundIdentifiers

The syntax-directed operation PrivateBoundIdentifiers takes no arguments and returns 一个字符串的 List. It is defined piecewise over the following productions:

FieldDefinition : ClassElementName Initializeropt
  1. 返回 ClassElementNamePrivateBoundIdentifiers
ClassElementName : PrivateIdentifier
  1. 返回一个 List,其唯一元素为 PrivateIdentifierStringValue
ClassElementName : PropertyName ClassElement : ClassStaticBlock ;
  1. 返回一个新的空 List
ClassElementList : ClassElementList ClassElement
  1. names1ClassElementListPrivateBoundIdentifiers
  2. names2ClassElementPrivateBoundIdentifiers
  3. 返回 names1names2 的列表拼接。
MethodDefinition : ClassElementName ( UniqueFormalParameters ) { FunctionBody } get ClassElementName ( ) { FunctionBody } set ClassElementName ( PropertySetParameterList ) { FunctionBody } GeneratorMethod : * ClassElementName ( UniqueFormalParameters ) { GeneratorBody } AsyncMethod : async ClassElementName ( UniqueFormalParameters ) { AsyncFunctionBody } AsyncGeneratorMethod : async * ClassElementName ( UniqueFormalParameters ) { AsyncGeneratorBody }
  1. 返回 ClassElementNamePrivateBoundIdentifiers

15.7.9 Static Semantics: ContainsArguments

The syntax-directed operation ContainsArguments takes no arguments and returns 一个布尔值.

本规范中未列在下面的每个文法产生式替代项,都隐式具有以下 ContainsArguments 默认定义:

  1. 对此解析节点的每个子节点 child,执行
    1. 如果 child 是非终结符的一个实例,则
      1. 如果 childContainsArgumentstrue,返回 true
  2. 返回 false
IdentifierReference : Identifier
  1. 如果 IdentifierStringValue"arguments",返回 true
  2. 返回 false
FunctionDeclaration : function BindingIdentifier ( FormalParameters ) { FunctionBody } function ( FormalParameters ) { FunctionBody } FunctionExpression : function BindingIdentifieropt ( FormalParameters ) { FunctionBody } GeneratorDeclaration : function * BindingIdentifier ( FormalParameters ) { GeneratorBody } function * ( FormalParameters ) { GeneratorBody } GeneratorExpression : function * BindingIdentifieropt ( FormalParameters ) { GeneratorBody } AsyncGeneratorDeclaration : async function * BindingIdentifier ( FormalParameters ) { AsyncGeneratorBody } async function * ( FormalParameters ) { AsyncGeneratorBody } AsyncGeneratorExpression : async function * BindingIdentifieropt ( FormalParameters ) { AsyncGeneratorBody } AsyncFunctionDeclaration : async function BindingIdentifier ( FormalParameters ) { AsyncFunctionBody } async function ( FormalParameters ) { AsyncFunctionBody } AsyncFunctionExpression : async function BindingIdentifieropt ( FormalParameters ) { AsyncFunctionBody }
  1. 返回 false
MethodDefinition : ClassElementName ( UniqueFormalParameters ) { FunctionBody } get ClassElementName ( ) { FunctionBody } set ClassElementName ( PropertySetParameterList ) { FunctionBody } GeneratorMethod : * ClassElementName ( UniqueFormalParameters ) { GeneratorBody } AsyncGeneratorMethod : async * ClassElementName ( UniqueFormalParameters ) { AsyncGeneratorBody } AsyncMethod : async ClassElementName ( UniqueFormalParameters ) { AsyncFunctionBody }
  1. 返回 ClassElementNameContainsArguments

15.7.10 Runtime Semantics: ClassFieldDefinitionEvaluation

The syntax-directed operation ClassFieldDefinitionEvaluation takes argument homeObject (一个 Object) and returns 要么是一个正常完成,其中包含一个 ClassFieldDefinition Record;要么是一个突然完成. It is defined piecewise over the following productions:

FieldDefinition : ClassElementName Initializeropt
  1. name 为 ? ClassElementNameEvaluation
  2. 如果 Initializer 存在,则
    1. formalParameterList 为产生式 FormalParameters : [empty] 的一个实例。
    2. env 为运行中执行上下文的 LexicalEnvironment。
    3. privateEnv 为运行中执行上下文的 PrivateEnvironment。
    4. sourceText 为空 Unicode 码点序列。
    5. initializerOrdinaryFunctionCreate(%Function.prototype%, sourceText, formalParameterList, Initializer, non-lexical-this, env, privateEnv)。
    6. 执行 MakeMethod(initializer, homeObject)。
    7. initializer.[[ClassFieldInitializerName]] 设为 name
  3. 否则,
    1. initializerempty
  4. 返回 ClassFieldDefinition Record { [[Name]]: name, [[Initializer]]: initializer }。
Note
initializer 创建的函数永远不能由 ECMAScript 代码直接访问。

15.7.11 Runtime Semantics: ClassStaticBlockDefinitionEvaluation

The syntax-directed operation ClassStaticBlockDefinitionEvaluation takes argument homeObject (一个 Object) and returns 一个 ClassStaticBlockDefinition Record. It is defined piecewise over the following productions:

ClassStaticBlock : static { ClassStaticBlockBody }
  1. lex 为运行中执行上下文的 LexicalEnvironment。
  2. privateEnv 为运行中执行上下文的 PrivateEnvironment。
  3. sourceText 为空 Unicode 码点序列。
  4. formalParameters 为产生式 FormalParameters : [empty] 的一个实例。
  5. bodyFunctionOrdinaryFunctionCreate(%Function.prototype%, sourceText, formalParameters, ClassStaticBlockBody, non-lexical-this, lex, privateEnv)。
  6. 执行 MakeMethod(bodyFunction, homeObject)。
  7. 返回 ClassStaticBlockDefinition Record { [[BodyFunction]]: bodyFunction }。
Note
函数 bodyFunction 永远不能由 ECMAScript 代码直接访问。

15.7.12 Runtime Semantics: EvaluateClassStaticBlockBody

The syntax-directed operation EvaluateClassStaticBlockBody takes argument functionObject (一个 ECMAScript 函数对象) and returns 一个返回完成或抛出完成. It is defined piecewise over the following productions:

ClassStaticBlockBody : ClassStaticBlockStatementList
  1. 断言:functionObject 是由 ClassStaticBlockDefinitionEvaluation 步骤 5 创建的合成函数。
  2. 执行 ! FunctionDeclarationInstantiation(functionObject, « »)。
  3. 执行 ? ClassStaticBlockStatementListEvaluation
  4. 返回 ReturnCompletion(undefined)。

15.7.13 Runtime Semantics: ClassElementEvaluation

The syntax-directed operation ClassElementEvaluation takes argument object (一个 Object) and returns 要么是一个正常完成,其中包含一个 ClassFieldDefinition Record、一个 ClassStaticBlockDefinition Record、一个 PrivateElementunused;要么是一个突然完成. It is defined piecewise over the following productions:

ClassElement : FieldDefinition ; static FieldDefinition ;
  1. 返回以 object 为参数的 FieldDefinition 的 ? ClassFieldDefinitionEvaluation
ClassElement : MethodDefinition static MethodDefinition
  1. 返回以 objectfalse 为参数的 MethodDefinition 的 ? MethodDefinitionEvaluation
ClassElement : ClassStaticBlock
  1. 返回以 object 为参数的 ClassStaticBlockClassStaticBlockDefinitionEvaluation
ClassElement : ;
  1. 返回 unused

15.7.14 Runtime Semantics: ClassDefinitionEvaluation

The syntax-directed operation ClassDefinitionEvaluation takes arguments classBinding (一个 String 或 undefined), className (一个属性键Private Name), and sourceText (ECMAScript 源文本) and returns 要么是一个正常完成,其中包含一个函数对象;要么是一个突然完成.

Note

为便于规范说明,私有方法和访问器与私有字段一起包含在类实例的 [[PrivateElements]] 槽中。然而,对于任一给定对象,要么具有由给定类定义的所有私有方法和访问器,要么一个也没有。此特性经过设计,使实现可以选择使用一种不需要单独跟踪每个方法或访问器的策略来实现私有方法和访问器。

例如,实现可以将实例私有方法直接与其对应的 Private Name 关联,并针对每个对象跟踪哪些类构造函数曾以该对象作为其 this 值运行。随后,在对象上查找实例私有方法就包括检查定义该方法的类构造函数是否已用于初始化该对象,然后返回与该 Private Name 关联的方法。

这不同于私有字段:由于字段初始化器可能在类实例化期间抛出,单个对象可能只具有给定类的私有字段的某个真子集,因此私有字段通常必须单独跟踪。

It is defined piecewise over the following productions:

ClassTail : ClassHeritageopt { ClassBodyopt }
  1. env 为运行中执行上下文的 LexicalEnvironment。
  2. classEnvNewDeclarativeEnvironment(env)。
  3. 如果 classBinding 不是 undefined,则
    1. 执行 ! classEnv.CreateImmutableBinding(classBinding, true)。
  4. outerPrivateEnvironment 为运行中执行上下文的 PrivateEnvironment。
  5. classPrivateEnvironmentNewPrivateEnvironment(outerPrivateEnvironment)。
  6. 如果 ClassBody 存在,则
    1. ClassBodyPrivateBoundIdentifiers 中的每个 String dn,执行
      1. 如果 classPrivateEnvironment.[[Names]] 包含一个 Private Name pn,使得 pn.[[Description]]dn,则
        1. 断言:这只可能发生于 getter/setter 对。
      2. 否则,
        1. name 为一个新的 Private Name,其 [[Description]]dn
        2. name 追加到 classPrivateEnvironment.[[Names]]
  7. 如果 ClassHeritage 不存在,则
    1. protoParent%Object.prototype%
    2. constructorParent%Function.prototype%
  8. 否则,
    1. 将运行中执行上下文的 LexicalEnvironment 设为 classEnv
    2. 注:在求值 ClassHeritage 时,运行中执行上下文的 PrivateEnvironment 为 outerPrivateEnvironment
    3. superclassRefCompletion(ClassHeritageEvaluation)。
    4. 将运行中执行上下文的 LexicalEnvironment 设为 env
    5. superclass 为 ? GetValue(? superclassRef)。
    6. 如果 superclassnull,则
      1. protoParentnull
      2. constructorParent%Function.prototype%
    7. 否则如果 IsConstructor(superclass) 为 false,则
      1. 抛出 TypeError 异常。
    8. 否则,
      1. protoParent 为 ? Get(superclass, "prototype")。
      2. 如果 protoParent 不是 Object 且 protoParent 不是 null,抛出 TypeError 异常。
      3. constructorParentsuperclass
  9. protoOrdinaryObjectCreate(protoParent)。
  10. 如果 ClassBody 不存在,令 constructorempty
  11. 否则,令 constructorClassBodyConstructorMethod
  12. 将运行中执行上下文的 LexicalEnvironment 设为 classEnv
  13. 将运行中执行上下文的 PrivateEnvironment 设为 classPrivateEnvironment
  14. 如果 constructorempty,则
    1. defaultConstructor 为一个新的 Abstract Closure,它没有参数,不捕获任何内容,并在被调用时执行以下步骤:
      1. args 为通过 [[Call]][[Construct]] 传递给此函数的参数 List
      2. 如果 NewTarget 为 undefined,抛出 TypeError 异常。
      3. constructorFunction活动函数对象
      4. 如果 constructorFunction.[[ConstructorKind]]derived,则
        1. 注:此分支的行为类似于 constructor(...args) { super(...args); }。最显著的区别是,前述 ECMAScript 源文本会可观察地调用 %Array.prototype% 上的 %Symbol.iterator% 方法,而此函数不会。
        2. func 为 ! constructorFunction.[[GetPrototypeOf]]()。
        3. 如果 IsConstructor(func) 为 false,抛出 TypeError 异常。
        4. result 为 ? Construct(func, args, NewTarget)。
      5. 否则,
        1. 注:此分支的行为类似于 constructor() {}
        2. result 为 ? OrdinaryCreateFromConstructor(NewTarget, "%Object.prototype%")。
      6. 执行 ? InitializeInstanceElements(result, constructorFunction)。
      7. 返回 NormalCompletion(result)。
    2. constructorFunctionCreateBuiltinFunction(defaultConstructor, 0, className, « [[ConstructorKind]], [[SourceText]], [[PrivateMethods]], [[Fields]] », 当前 Realm Record, constructorParent)。
  15. 否则,
    1. constructorInfo 为以 protoconstructorParent 为参数的 constructor 的 ! DefineMethod
    2. constructorFunctionconstructorInfo.[[Closure]]
    3. 执行 MakeClassConstructor(constructorFunction)。
    4. 执行 SetFunctionName(constructorFunction, className)。
  16. constructorFunction.[[SourceText]] 设为 sourceText
  17. 执行 MakeConstructor(constructorFunction, false, proto)。
  18. 如果 ClassHeritage 存在,将 constructorFunction.[[ConstructorKind]] 设为 derived
  19. 执行 ! DefineMethodProperty(proto, "constructor", constructorFunction, false)。
  20. 如果 ClassBody 不存在,令 elements 为一个新的空 List
  21. 否则,令 elementsClassBodyNonConstructorElements
  22. instancePrivateMethods 为一个新的空 List
  23. staticPrivateMethods 为一个新的空 List
  24. instanceFields 为一个新的空 List
  25. staticElements 为一个新的空 List
  26. elements 的每个 ClassElement e,执行
    1. 如果 eIsStaticfalse,则
      1. elementCompletion(以 proto 为参数的 eClassElementEvaluation)。
    2. 否则,
      1. elementCompletion(以 constructorFunction 为参数的 eClassElementEvaluation)。
    3. 如果 element 是突然完成,则
      1. 将运行中执行上下文的 LexicalEnvironment 设为 env
      2. 将运行中执行上下文的 PrivateEnvironment 设为 outerPrivateEnvironment
      3. 返回 ? element
    4. element 设为 ! element
    5. 如果 elementPrivateElement,则
      1. 断言:element.[[Kind]]methodaccessor
      2. 如果 eIsStaticfalse,令 containerinstancePrivateMethods
      3. 否则,令 containerstaticPrivateMethods
      4. 如果 container 包含一个 PrivateElement pe,使得 pe.[[Key]]element.[[Key]],则
        1. 断言:element.[[Kind]]pe.[[Kind]] 都是 accessor
        2. 如果 element.[[Get]]undefined,则
          1. combinedPrivateElement { [[Key]]: element.[[Key]], [[Kind]]: accessor, [[Get]]: pe.[[Get]], [[Set]]: element.[[Set]] }。
        3. 否则,
          1. combinedPrivateElement { [[Key]]: element.[[Key]], [[Kind]]: accessor, [[Get]]: element.[[Get]], [[Set]]: pe.[[Set]] }。
        4. combined 替换 container 中的 pe
      5. 否则,
        1. element 追加到 container
    6. 否则如果 elementClassFieldDefinition Record,则
      1. 如果 eIsStaticfalse,将 element 追加到 instanceFields
      2. 否则,将 element 追加到 staticElements
    7. 否则如果 element 是 ClassStaticBlockDefinition Record,则
      1. element 追加到 staticElements
  27. 将运行中执行上下文的 LexicalEnvironment 设为 env
  28. 如果 classBinding 不是 undefined,则
    1. 执行 ! classEnv.InitializeBinding(classBinding, constructorFunction)。
  29. constructorFunction.[[PrivateMethods]] 设为 instancePrivateMethods
  30. constructorFunction.[[Fields]] 设为 instanceFields
  31. staticPrivateMethods 的每个 PrivateElement method,执行
    1. 执行 ! PrivateMethodOrAccessorAdd(constructorFunction, method)。
  32. staticElements 的每个元素 elementRecord,执行
    1. 如果 elementRecordClassFieldDefinition Record,则
      1. resultCompletion(DefineField(constructorFunction, elementRecord))。
    2. 否则,
      1. 断言:elementRecord 是 ClassStaticBlockDefinition Record
      2. resultCompletion(Call(elementRecord.[[BodyFunction]], constructorFunction))。
    3. 如果 result 是突然完成,则
      1. 将运行中执行上下文的 PrivateEnvironment 设为 outerPrivateEnvironment
      2. 返回 ? result
  33. 将运行中执行上下文的 PrivateEnvironment 设为 outerPrivateEnvironment
  34. 返回 constructorFunction

15.7.15 Runtime Semantics: BindingClassDeclarationEvaluation

The syntax-directed operation BindingClassDeclarationEvaluation takes no arguments and returns 要么是一个正常完成,其中包含一个函数对象;要么是一个突然完成. It is defined piecewise over the following productions:

ClassDeclaration : class BindingIdentifier ClassTail
  1. classNameBindingIdentifierStringValue
  2. sourceTextClassDeclaration匹配的源文本
  3. value 为以 classNameclassNamesourceText 为参数的 ClassTail 的 ? ClassDefinitionEvaluation
  4. env 为运行中执行上下文的 LexicalEnvironment。
  5. 执行 ? InitializeBoundName(className, value, env)。
  6. 返回 value
ClassDeclaration : class ClassTail
  1. sourceTextClassDeclaration匹配的源文本
  2. 返回以 undefined"default"sourceText 为参数的 ClassTail 的 ? ClassDefinitionEvaluation
Note

ClassDeclaration : class ClassTail 只作为 ExportDeclaration 的一部分出现,其绑定的建立作为该产生式求值动作的一部分处理。参见 16.2.3.7

15.7.16 Runtime Semantics: Evaluation

ClassDeclaration : class BindingIdentifier ClassTail
  1. 执行此 ClassDeclaration 的 ? BindingClassDeclarationEvaluation
  2. 返回 empty
Note

ClassDeclaration : class ClassTail 只作为 ExportDeclaration 的一部分出现,并且从不被直接求值。

ClassExpression : class ClassTail
  1. sourceTextClassExpression匹配的源文本
  2. 返回以 undefined、空 String 和 sourceText 为参数的 ClassTail 的 ? ClassDefinitionEvaluation
ClassExpression : class BindingIdentifier ClassTail
  1. classNameBindingIdentifierStringValue
  2. sourceTextClassExpression匹配的源文本
  3. 返回以 classNameclassNamesourceText 为参数的 ClassTail 的 ? ClassDefinitionEvaluation
ClassElementName : PrivateIdentifier
  1. privateIdentifierPrivateIdentifierStringValue
  2. privateEnvRec 为运行中执行上下文的 PrivateEnvironment。
  3. namesprivateEnvRec.[[Names]]
  4. 断言:names 中恰有一个元素是 [[Description]]privateIdentifierPrivate Name
  5. privateNamenames[[Description]]privateIdentifierPrivate Name
  6. 返回 privateName
ClassStaticBlockStatementList : [empty]
  1. 返回 undefined

15.8 异步函数定义

语法

AsyncFunctionDeclaration[Yield, Await, Default] : async [no LineTerminator here] function BindingIdentifier[?Yield, ?Await] ( FormalParameters[~Yield, +Await] ) { AsyncFunctionBody } [+Default] async [no LineTerminator here] function ( FormalParameters[~Yield, +Await] ) { AsyncFunctionBody } AsyncFunctionExpression : async [no LineTerminator here] function BindingIdentifier[~Yield, +Await]opt ( FormalParameters[~Yield, +Await] ) { AsyncFunctionBody } AsyncMethod[Yield, Await] : async [no LineTerminator here] ClassElementName[?Yield, ?Await] ( UniqueFormalParameters[~Yield, +Await] ) { AsyncFunctionBody } AsyncFunctionBody : FunctionBody[~Yield, +Await] AwaitExpression[Yield] : await UnaryExpression[?Yield, +Await] Note 1

[Await] 参数存在时,await 被解析为 AwaitExpression关键字[Await] 参数存在于以下上下文的顶层,尽管根据非终结符(例如 FunctionBody)不同,该参数在某些上下文中可能不存在:

Script 是语法目标符号时,若 [Await] 参数不存在,await 可以被解析为标识符。这包括以下上下文:

Note 2

YieldExpression 不同,省略 AwaitExpression 的操作数是语法错误。必须 await 某个东西。

15.8.1 Static Semantics: 早期错误

AsyncMethod : async ClassElementName ( UniqueFormalParameters ) { AsyncFunctionBody } AsyncFunctionDeclaration : async function BindingIdentifier ( FormalParameters ) { AsyncFunctionBody } async function ( FormalParameters ) { AsyncFunctionBody } AsyncFunctionExpression : async function BindingIdentifieropt ( FormalParameters ) { AsyncFunctionBody }

15.8.2 Runtime Semantics: InstantiateAsyncFunctionObject

The syntax-directed operation InstantiateAsyncFunctionObject takes arguments env (一个 Environment Record) and privateEnv (一个 PrivateEnvironment Recordnull) and returns 一个 ECMAScript 函数对象. It is defined piecewise over the following productions:

AsyncFunctionDeclaration : async function BindingIdentifier ( FormalParameters ) { AsyncFunctionBody }
  1. nameBindingIdentifierStringValue
  2. sourceTextAsyncFunctionDeclaration匹配的源文本
  3. closureOrdinaryFunctionCreate(%AsyncFunction.prototype%, sourceText, FormalParameters, AsyncFunctionBody, non-lexical-this, env, privateEnv)。
  4. 执行 SetFunctionName(closure, name)。
  5. 返回 closure
AsyncFunctionDeclaration : async function ( FormalParameters ) { AsyncFunctionBody }
  1. sourceTextAsyncFunctionDeclaration匹配的源文本
  2. closureOrdinaryFunctionCreate(%AsyncFunction.prototype%, sourceText, FormalParameters, AsyncFunctionBody, non-lexical-this, env, privateEnv)。
  3. 执行 SetFunctionName(closure, "default")。
  4. 返回 closure

15.8.3 Runtime Semantics: InstantiateAsyncFunctionExpression

The syntax-directed operation InstantiateAsyncFunctionExpression takes optional argument name (一个属性键Private Name) and returns 一个 ECMAScript 函数对象. It is defined piecewise over the following productions:

AsyncFunctionExpression : async function ( FormalParameters ) { AsyncFunctionBody }
  1. 如果 name 不存在,则将 name 设为空 String。
  2. env 为运行中执行上下文的 LexicalEnvironment。
  3. privateEnv 为运行中执行上下文的 PrivateEnvironment。
  4. sourceTextAsyncFunctionExpression匹配的源文本
  5. closureOrdinaryFunctionCreate(%AsyncFunction.prototype%, sourceText, FormalParameters, AsyncFunctionBody, non-lexical-this, env, privateEnv)。
  6. 执行 SetFunctionName(closure, name)。
  7. 返回 closure
AsyncFunctionExpression : async function BindingIdentifier ( FormalParameters ) { AsyncFunctionBody }
  1. 断言:name 不存在。
  2. name 设为 BindingIdentifierStringValue
  3. outerEnv 为运行中执行上下文的 LexicalEnvironment。
  4. funcEnvNewDeclarativeEnvironment(outerEnv)。
  5. 执行 ! funcEnv.CreateImmutableBinding(name, false)。
  6. privateEnv 为运行中执行上下文的 PrivateEnvironment。
  7. sourceTextAsyncFunctionExpression匹配的源文本
  8. closureOrdinaryFunctionCreate(%AsyncFunction.prototype%, sourceText, FormalParameters, AsyncFunctionBody, non-lexical-this, funcEnv, privateEnv)。
  9. 执行 SetFunctionName(closure, name)。
  10. 执行 ! funcEnv.InitializeBinding(name, closure)。
  11. 返回 closure
Note

AsyncFunctionExpression 中的 BindingIdentifier 可在 AsyncFunctionExpressionAsyncFunctionBody 内被引用,以允许函数递归调用自身。然而,与 FunctionDeclaration 中不同,AsyncFunctionExpression 中的 BindingIdentifier 不能从外围作用域引用,也不会影响包围 AsyncFunctionExpression 的作用域。

15.8.4 Runtime Semantics: EvaluateAsyncFunctionBody

The syntax-directed operation EvaluateAsyncFunctionBody takes arguments functionObject (一个 ECMAScript 函数对象) and argumentsList (ECMAScript 语言值List) and returns 一个返回完成. It is defined piecewise over the following productions:

AsyncFunctionBody : FunctionBody
  1. promiseCapability 为 ! NewPromiseCapability(%Promise%)。
  2. completionCompletion(FunctionDeclarationInstantiation(functionObject, argumentsList))。
  3. 如果 completion 是突然完成,则
    1. 执行 ! Call(promiseCapability.[[Reject]], undefined, « completion.[[Value]] »)。
  4. 否则,
    1. 执行 AsyncFunctionStart(promiseCapability, FunctionBody)。
  5. 返回 ReturnCompletion(promiseCapability.[[Promise]])。

15.8.5 Runtime Semantics: Evaluation

AsyncFunctionExpression : async function BindingIdentifieropt ( FormalParameters ) { AsyncFunctionBody }
  1. 返回 AsyncFunctionExpressionInstantiateAsyncFunctionExpression
AwaitExpression : await UnaryExpression
  1. exprRef 为 ? UnaryExpressionEvaluation
  2. value 为 ? GetValue(exprRef)。
  3. 返回 ? Await(value)。

15.9 异步箭头函数定义

语法

AsyncArrowFunction[In, Yield, Await] : async [no LineTerminator here] AsyncArrowBindingIdentifier[?Yield] [no LineTerminator here] => AsyncConciseBody[?In] CoverCallExpressionAndAsyncArrowHead[?Yield, ?Await] [no LineTerminator here] => AsyncConciseBody[?In] AsyncConciseBody[In] : [lookahead ≠ {] ExpressionBody[?In, +Await] { AsyncFunctionBody } AsyncArrowBindingIdentifier[Yield] : BindingIdentifier[?Yield, +Await] CoverCallExpressionAndAsyncArrowHead[Yield, Await] : MemberExpression[?Yield, ?Await] Arguments[?Yield, ?Await]

补充语法

当处理产生式的一个实例
AsyncArrowFunction : CoverCallExpressionAndAsyncArrowHead => AsyncConciseBody
时,使用以下文法来细化对 CoverCallExpressionAndAsyncArrowHead 的解释:

AsyncArrowHead : async [no LineTerminator here] ArrowFormalParameters[~Yield, +Await]

15.9.1 Static Semantics: 早期错误

AsyncArrowFunction : async AsyncArrowBindingIdentifier => AsyncConciseBody AsyncArrowFunction : CoverCallExpressionAndAsyncArrowHead => AsyncConciseBody

15.9.2 Static Semantics: AsyncConciseBodyContainsUseStrict

The syntax-directed operation AsyncConciseBodyContainsUseStrict takes no arguments and returns 一个布尔值. It is defined piecewise over the following productions:

AsyncConciseBody : ExpressionBody
  1. 返回 false
AsyncConciseBody : { AsyncFunctionBody }
  1. 返回 AsyncFunctionBodyFunctionBodyContainsUseStrict

15.9.3 Runtime Semantics: EvaluateAsyncConciseBody

The syntax-directed operation EvaluateAsyncConciseBody takes arguments functionObject (一个 ECMAScript 函数对象) and argumentsList (ECMAScript 语言值List) and returns 一个返回完成. It is defined piecewise over the following productions:

AsyncConciseBody : ExpressionBody
  1. promiseCapability 为 ! NewPromiseCapability(%Promise%)。
  2. completionCompletion(FunctionDeclarationInstantiation(functionObject, argumentsList))。
  3. 如果 completion 是突然完成,则
    1. 执行 ! Call(promiseCapability.[[Reject]], undefined, « completion.[[Value]] »)。
  4. 否则,
    1. 执行 AsyncFunctionStart(promiseCapability, ExpressionBody)。
  5. 返回 ReturnCompletion(promiseCapability.[[Promise]])。

15.9.4 Runtime Semantics: InstantiateAsyncArrowFunctionExpression

The syntax-directed operation InstantiateAsyncArrowFunctionExpression takes optional argument name (一个属性键Private Name) and returns 一个 ECMAScript 函数对象. It is defined piecewise over the following productions:

AsyncArrowFunction : async AsyncArrowBindingIdentifier => AsyncConciseBody
  1. 如果 name 不存在,则将 name 设为空 String。
  2. env 为运行中执行上下文的 LexicalEnvironment。
  3. privateEnv 为运行中执行上下文的 PrivateEnvironment。
  4. sourceTextAsyncArrowFunction匹配的源文本
  5. parametersAsyncArrowBindingIdentifier
  6. closureOrdinaryFunctionCreate(%AsyncFunction.prototype%, sourceText, parameters, AsyncConciseBody, lexical-this, env, privateEnv)。
  7. 执行 SetFunctionName(closure, name)。
  8. 返回 closure
AsyncArrowFunction : CoverCallExpressionAndAsyncArrowHead => AsyncConciseBody
  1. 如果 name 不存在,则将 name 设为空 String。
  2. env 为运行中执行上下文的 LexicalEnvironment。
  3. privateEnv 为运行中执行上下文的 PrivateEnvironment。
  4. sourceTextAsyncArrowFunction匹配的源文本
  5. headCoverCallExpressionAndAsyncArrowHead覆盖AsyncArrowHead
  6. parametersheadArrowFormalParameters
  7. closureOrdinaryFunctionCreate(%AsyncFunction.prototype%, sourceText, parameters, AsyncConciseBody, lexical-this, env, privateEnv)。
  8. 执行 SetFunctionName(closure, name)。
  9. 返回 closure

15.9.5 Runtime Semantics: Evaluation

AsyncArrowFunction : async AsyncArrowBindingIdentifier => AsyncConciseBody CoverCallExpressionAndAsyncArrowHead => AsyncConciseBody
  1. 返回 AsyncArrowFunctionInstantiateAsyncArrowFunctionExpression

15.10 尾位置调用

15.10.1 Static Semantics: IsInTailPosition ( call )

The abstract operation IsInTailPosition takes argument call (一个 CallExpression 解析节点、一个 MemberExpression 解析节点或一个 OptionalChain 解析节点) and returns 一个布尔值. It performs the following steps when called:

  1. 如果 IsStrict(call) 为 false,返回 false
  2. 如果 call 未包含在 FunctionBodyConciseBodyAsyncConciseBody 内,返回 false
  3. body 为最紧密包含 callFunctionBodyConciseBodyAsyncConciseBody
  4. 如果 bodyGeneratorBodyFunctionBody,返回 false
  5. 如果 bodyAsyncFunctionBodyFunctionBody,返回 false
  6. 如果 bodyAsyncGeneratorBodyFunctionBody,返回 false
  7. 如果 bodyAsyncConciseBody,返回 false
  8. 返回以 call 为参数的 bodyHasCallInTailPosition 的结果。
Note

尾位置调用只在严格模式代码中定义,因为存在一种常见的非标准语言扩展(参见 10.2.4),该扩展允许观察调用者上下文链。

15.10.2 Static Semantics: HasCallInTailPosition

The syntax-directed operation HasCallInTailPosition takes argument call (一个 CallExpression 解析节点、一个 MemberExpression 解析节点或一个 OptionalChain 解析节点) and returns 一个布尔值.

Note 1

call 是表示特定源文本范围的解析节点。当以下算法将 call 与另一个解析节点比较时,这是在测试它们是否表示同一段源文本。

Note 2

紧随其后返回调用结果的 GetValue 的潜在尾位置调用,也是一种可能的尾位置调用。函数调用不能返回 Reference Record,因此这样的 GetValue 操作总是会返回与实际函数调用结果相同的值。

It is defined piecewise over the following productions:

StatementList : StatementList StatementListItem
  1. has 为以 call 为参数的 StatementListHasCallInTailPosition
  2. 如果 hastrue,返回 true
  3. 返回以 call 为参数的 StatementListItemHasCallInTailPosition
FunctionStatementList : [empty] StatementListItem : Declaration Statement : VariableStatement EmptyStatement ExpressionStatement ContinueStatement BreakStatement ThrowStatement DebuggerStatement Block : { } ReturnStatement : return ; LabelledItem : FunctionDeclaration ForInOfStatement : for ( LeftHandSideExpression of AssignmentExpression ) Statement for ( var ForBinding of AssignmentExpression ) Statement for ( ForDeclaration of AssignmentExpression ) Statement CaseBlock : { }
  1. 返回 false
IfStatement : if ( Expression ) Statement else Statement
  1. has 为以 call 为参数的第一个 StatementHasCallInTailPosition
  2. 如果 hastrue,返回 true
  3. 返回以 call 为参数的第二个 StatementHasCallInTailPosition
IfStatement : if ( Expression ) Statement DoWhileStatement : do Statement while ( Expression ) ; WhileStatement : while ( Expression ) Statement ForStatement : for ( Expressionopt ; Expressionopt ; Expressionopt ) Statement for ( var VariableDeclarationList ; Expressionopt ; Expressionopt ) Statement for ( LexicalDeclaration Expressionopt ; Expressionopt ) Statement ForInOfStatement : for ( LeftHandSideExpression in Expression ) Statement for ( var ForBinding in Expression ) Statement for ( ForDeclaration in Expression ) Statement WithStatement : with ( Expression ) Statement
  1. 返回以 call 为参数的 StatementHasCallInTailPosition
LabelledStatement : LabelIdentifier : LabelledItem
  1. 返回以 call 为参数的 LabelledItemHasCallInTailPosition
ReturnStatement : return Expression ;
  1. 返回以 call 为参数的 ExpressionHasCallInTailPosition
SwitchStatement : switch ( Expression ) CaseBlock
  1. 返回以 call 为参数的 CaseBlockHasCallInTailPosition
CaseBlock : { CaseClausesopt DefaultClause CaseClausesopt }
  1. hasfalse
  2. 如果第一个 CaseClauses 存在,将 has 设为以 call 为参数的第一个 CaseClausesHasCallInTailPosition
  3. 如果 hastrue,返回 true
  4. has 设为以 call 为参数的 DefaultClauseHasCallInTailPosition
  5. 如果 hastrue,返回 true
  6. 如果第二个 CaseClauses 存在,将 has 设为以 call 为参数的第二个 CaseClausesHasCallInTailPosition
  7. 返回 has
CaseClauses : CaseClauses CaseClause
  1. has 为以 call 为参数的 CaseClausesHasCallInTailPosition
  2. 如果 hastrue,返回 true
  3. 返回以 call 为参数的 CaseClauseHasCallInTailPosition
CaseClause : case Expression : StatementListopt DefaultClause : default : StatementListopt
  1. 如果 StatementList 存在,返回以 call 为参数的 StatementListHasCallInTailPosition
  2. 返回 false
TryStatement : try Block Catch
  1. 返回以 call 为参数的 CatchHasCallInTailPosition
TryStatement : try Block Finally try Block Catch Finally
  1. 返回以 call 为参数的 FinallyHasCallInTailPosition
Catch : catch ( CatchParameter ) Block
  1. 返回以 call 为参数的 BlockHasCallInTailPosition
AssignmentExpression : YieldExpression ArrowFunction AsyncArrowFunction LeftHandSideExpression = AssignmentExpression LeftHandSideExpression AssignmentOperator AssignmentExpression LeftHandSideExpression &&= AssignmentExpression LeftHandSideExpression ||= AssignmentExpression LeftHandSideExpression ??= AssignmentExpression BitwiseANDExpression : BitwiseANDExpression & EqualityExpression BitwiseXORExpression : BitwiseXORExpression ^ BitwiseANDExpression BitwiseORExpression : BitwiseORExpression | BitwiseXORExpression EqualityExpression : EqualityExpression == RelationalExpression EqualityExpression != RelationalExpression EqualityExpression === RelationalExpression EqualityExpression !== RelationalExpression RelationalExpression : RelationalExpression < ShiftExpression RelationalExpression > ShiftExpression RelationalExpression <= ShiftExpression RelationalExpression >= ShiftExpression RelationalExpression instanceof ShiftExpression RelationalExpression in ShiftExpression PrivateIdentifier in ShiftExpression ShiftExpression : ShiftExpression << AdditiveExpression ShiftExpression >> AdditiveExpression ShiftExpression >>> AdditiveExpression AdditiveExpression : AdditiveExpression + MultiplicativeExpression AdditiveExpression - MultiplicativeExpression MultiplicativeExpression : MultiplicativeExpression MultiplicativeOperator ExponentiationExpression ExponentiationExpression : UpdateExpression ** ExponentiationExpression UpdateExpression : LeftHandSideExpression ++ LeftHandSideExpression -- ++ UnaryExpression -- UnaryExpression UnaryExpression : delete UnaryExpression void UnaryExpression typeof UnaryExpression + UnaryExpression - UnaryExpression ~ UnaryExpression ! UnaryExpression AwaitExpression CallExpression : SuperCall ImportCall CallExpression [ Expression ] CallExpression . IdentifierName CallExpression . PrivateIdentifier NewExpression : new NewExpression MemberExpression : MemberExpression [ Expression ] MemberExpression . IdentifierName SuperProperty MetaProperty new MemberExpression Arguments MemberExpression . PrivateIdentifier PrimaryExpression : this IdentifierReference Literal ArrayLiteral ObjectLiteral FunctionExpression ClassExpression GeneratorExpression AsyncFunctionExpression AsyncGeneratorExpression RegularExpressionLiteral TemplateLiteral
  1. 返回 false
Expression : AssignmentExpression Expression , AssignmentExpression
  1. 返回以 call 为参数的 AssignmentExpressionHasCallInTailPosition
ConditionalExpression : ShortCircuitExpression ? AssignmentExpression : AssignmentExpression
  1. has 为以 call 为参数的第一个 AssignmentExpressionHasCallInTailPosition
  2. 如果 hastrue,返回 true
  3. 返回以 call 为参数的第二个 AssignmentExpressionHasCallInTailPosition
LogicalANDExpression : LogicalANDExpression && BitwiseORExpression
  1. 返回以 call 为参数的 BitwiseORExpressionHasCallInTailPosition
LogicalORExpression : LogicalORExpression || LogicalANDExpression
  1. 返回以 call 为参数的 LogicalANDExpressionHasCallInTailPosition
CoalesceExpression : CoalesceExpressionHead ?? BitwiseORExpression
  1. 返回以 call 为参数的 BitwiseORExpressionHasCallInTailPosition
CallExpression : CoverCallExpressionAndAsyncArrowHead CallExpression Arguments CallExpression TemplateLiteral
  1. 如果此 CallExpressioncall,返回 true
  2. 返回 false
OptionalExpression : MemberExpression OptionalChain CallExpression OptionalChain OptionalExpression OptionalChain
  1. 返回以 call 为参数的 OptionalChainHasCallInTailPosition
OptionalChain : ?. [ Expression ] ?. IdentifierName ?. PrivateIdentifier OptionalChain [ Expression ] OptionalChain . IdentifierName OptionalChain . PrivateIdentifier
  1. 返回 false
OptionalChain : ?. Arguments OptionalChain Arguments
  1. 如果此 OptionalChaincall,返回 true
  2. 返回 false
MemberExpression : MemberExpression TemplateLiteral
  1. 如果此 MemberExpressioncall,返回 true
  2. 返回 false
PrimaryExpression : CoverParenthesizedExpressionAndArrowParameterList
  1. exprCoverParenthesizedExpressionAndArrowParameterList覆盖ParenthesizedExpression
  2. 返回以 call 为参数的 exprHasCallInTailPosition
ParenthesizedExpression : ( Expression )
  1. 返回以 call 为参数的 ExpressionHasCallInTailPosition

15.10.3 PrepareForTailCall ( )

The abstract operation PrepareForTailCall takes no arguments and returns unused. It performs the following steps when called:

  1. 断言:当前执行上下文随后不会再用于求值任何 ECMAScript 代码或内置函数。在调用此抽象操作之后对 Call 的调用,会在执行任何此类求值之前创建并推入一个新的执行上下文
  2. 丢弃与当前执行上下文关联的所有资源。
  3. 返回 unused

尾位置调用必须在调用目标函数之前释放与当前正在执行的函数执行上下文关联的任何瞬时内部资源,或者重用这些资源以支持目标函数。

Note

例如,尾位置调用应当只让实现的活动记录栈增长目标函数活动记录大小超出调用函数活动记录大小的那部分。如果目标函数的活动记录更小,则栈的总大小应当减少。