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

同一个 BindingIdentifierFormalParameterList 中多次出现,只允许用于具有简单参数列表且不是在严格模式代码中定义的函数。

15.1.2 Static Semantics: ContainsExpression

The syntax-directed operation ContainsExpression takes no arguments and returns a Boolean. 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 a Boolean. 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 a Boolean. 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 a non-negative integer. 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 的数量。第一个带有 initializer 的形参之后允许出现没有 initializer 的 FormalParameter,但这类形参会被视为以 undefined 作为默认值的可选形参。

FormalParameterList : FormalParameter
  1. 如果 FormalParameterHasInitializertrue,则返回 0。
  2. 返回 1。
FormalParameterList : FormalParameterList , FormalParameter
  1. countFormalParameterListExpectedArgumentCount
  2. 如果 FormalParameterListHasInitializertrue,或 FormalParameterHasInitializertrue,则返回 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 或函数声明绑定的标识符。

FunctionBody : FunctionStatementList

15.2.2 Static Semantics: FunctionBodyContainsUseStrict

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

FunctionBody : FunctionStatementList
  1. 如果 FunctionBodyDirective Prologue 包含 Use Strict Directive,则返回 true
  2. 返回 false

15.2.3 Runtime Semantics: EvaluateFunctionBody

The syntax-directed operation EvaluateFunctionBody takes arguments funcObj (an ECMAScript function object) and argList (a List of ECMAScript language values) and returns a return completion or a throw completion. It is defined piecewise over the following productions:

FunctionBody : FunctionStatementList
  1. 执行 ? FunctionDeclarationInstantiation(funcObj, argList)。
  2. 执行 ? FunctionStatementListEvaluation
  3. 注:如果前一步产生了 normal completion,则求值是通过越过 FunctionStatementList 末尾而完成的。
  4. 返回 ReturnCompletion(undefined)。

15.2.4 Runtime Semantics: InstantiateOrdinaryFunctionObject

The syntax-directed operation InstantiateOrdinaryFunctionObject takes arguments envRecord (an Environment Record) and privateEnv (a PrivateEnvironment Record or null) and returns an ECMAScript function object. It is defined piecewise over the following productions:

FunctionDeclaration : function BindingIdentifier ( FormalParameters ) { FunctionBody }
  1. nameBindingIdentifierStringValue
  2. sourceText 为由 FunctionDeclaration 匹配的源文本
  3. closureOrdinaryFunctionCreate(%Function.prototype%, sourceText, FormalParameters, FunctionBody, non-lexical-this, envRecord, privateEnv)。
  4. 执行 SetFunctionName(closure, name)。
  5. 执行 MakeConstructor(closure)。
  6. 返回 closure
FunctionDeclaration : function ( FormalParameters ) { FunctionBody }
  1. sourceText 为由 FunctionDeclaration 匹配的源文本
  2. closureOrdinaryFunctionCreate(%Function.prototype%, sourceText, FormalParameters, FunctionBody, non-lexical-this, envRecord, 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 (a property key or a Private Name) and returns an ECMAScript function object. It is defined piecewise over the following productions:

FunctionExpression : function ( FormalParameters ) { FunctionBody }
  1. 如果 name 不存在,则将 name 设置为空 String。
  2. envRecord 为运行中的执行上下文的 LexicalEnvironment。
  3. privateEnv 为运行中的执行上下文的 PrivateEnvironment。
  4. sourceText 为由 FunctionExpression 匹配的源文本
  5. closureOrdinaryFunctionCreate(%Function.prototype%, sourceText, FormalParameters, FunctionBody, non-lexical-this, envRecord, 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. sourceText 为由 FunctionExpression 匹配的源文本
  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 内部引用,以允许函数递归调用自身。不过,不同于 FunctionDeclarationFunctionExpression 中的 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
FunctionStatementList : StatementList
  1. resultStatementList 的求值的 Completion
  2. env 为运行中执行上下文的 LexicalEnvironment。
  3. 断言:env 是声明式环境记录。
  4. 返回 ? DisposeResources(env.[[DisposableResourceStack]], result)。

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 a Boolean. 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 funcObj (an ECMAScript function object) and argList (a List of ECMAScript language values) and returns a return completion or a throw completion. It is defined piecewise over the following productions:

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

15.3.4 Runtime Semantics: InstantiateArrowFunctionExpression

The syntax-directed operation InstantiateArrowFunctionExpression takes optional argument name (a property key or a Private Name) and returns an ECMAScript function object. It is defined piecewise over the following productions:

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

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

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 a Boolean. 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 a Boolean. 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 obj (an Object) and optional argument proto (an Object) and returns either a normal completion containing a Record with fields [[Key]] (a property key) and [[Closure]] (an ECMAScript function object) or an abrupt completion. It is defined piecewise over the following productions:

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

15.4.5 Runtime Semantics: MethodDefinitionEvaluation

The syntax-directed operation MethodDefinitionEvaluation takes arguments obj (an Object) and enumerable (a Boolean) and returns either a normal completion containing either a PrivateElement or unused, or an abrupt completion. It is defined piecewise over the following productions:

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

与 Generators 相关的抽象操作定义在 27.8.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 funcObj (an ECMAScript function object) and argList (a List of ECMAScript language values) and returns a throw completion or a return completion. It is defined piecewise over the following productions:

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

15.5.3 Runtime Semantics: InstantiateGeneratorFunctionObject

The syntax-directed operation InstantiateGeneratorFunctionObject takes arguments envRecord (an Environment Record) and privateEnv (a PrivateEnvironment Record or null) and returns an ECMAScript function object. It is defined piecewise over the following productions:

GeneratorDeclaration : function * BindingIdentifier ( FormalParameters ) { GeneratorBody }
  1. nameBindingIdentifierStringValue
  2. sourceText 为由 GeneratorDeclaration 匹配的源文本
  3. closureOrdinaryFunctionCreate(%GeneratorFunction.prototype%, sourceText, FormalParameters, GeneratorBody, non-lexical-this, envRecord, privateEnv)。
  4. 执行 SetFunctionName(closure, name)。
  5. protoOrdinaryObjectCreate(%GeneratorPrototype%)。
  6. 执行 ! DefinePropertyOrThrow(closure, "prototype", PropertyDescriptor { [[Value]]: proto, [[Writable]]: true, [[Enumerable]]: false, [[Configurable]]: false })。
  7. 返回 closure
GeneratorDeclaration : function * ( FormalParameters ) { GeneratorBody }
  1. sourceText 为由 GeneratorDeclaration 匹配的源文本
  2. closureOrdinaryFunctionCreate(%GeneratorFunction.prototype%, sourceText, FormalParameters, GeneratorBody, non-lexical-this, envRecord, privateEnv)。
  3. 执行 SetFunctionName(closure, "default")。
  4. protoOrdinaryObjectCreate(%GeneratorPrototype%)。
  5. 执行 ! DefinePropertyOrThrow(closure, "prototype", PropertyDescriptor { [[Value]]: proto, [[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 (a property key or a Private Name) and returns an ECMAScript function object. It is defined piecewise over the following productions:

GeneratorExpression : function * ( FormalParameters ) { GeneratorBody }
  1. 如果 name 不存在,则将 name 设置为空 String。
  2. envRecord 为运行中的执行上下文的 LexicalEnvironment。
  3. privateEnv 为运行中的执行上下文的 PrivateEnvironment。
  4. sourceText 为由 GeneratorExpression 匹配的源文本
  5. closureOrdinaryFunctionCreate(%GeneratorFunction.prototype%, sourceText, FormalParameters, GeneratorBody, non-lexical-this, envRecord, privateEnv)。
  6. 执行 SetFunctionName(closure, name)。
  7. protoOrdinaryObjectCreate(%GeneratorPrototype%)。
  8. 执行 ! DefinePropertyOrThrow(closure, "prototype", PropertyDescriptor { [[Value]]: proto, [[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. sourceText 为由 GeneratorExpression 匹配的源文本
  8. closureOrdinaryFunctionCreate(%GeneratorFunction.prototype%, sourceText, FormalParameters, GeneratorBody, non-lexical-this, funcEnv, privateEnv)。
  9. 执行 SetFunctionName(closure, name)。
  10. protoOrdinaryObjectCreate(%GeneratorPrototype%)。
  11. 执行 ! DefinePropertyOrThrow(closure, "prototype", PropertyDescriptor { [[Value]]: proto, [[Writable]]: true, [[Enumerable]]: false, [[Configurable]]: false })。
  12. 执行 ! funcEnv.InitializeBinding(name, closure)。
  13. 返回 closure
Note

GeneratorExpression 中的 BindingIdentifier 可以从该 GeneratorExpressionFunctionBody 内部引用,以允许生成器代码递归调用自身。不过,不同于 GeneratorDeclarationGeneratorExpression 中的 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. genKindGetGeneratorKind()。
  2. 断言:genKindsyncasync
  3. exprRef 为 ? AssignmentExpressionEvaluation
  4. value 为 ? GetValue(exprRef)。
  5. iteratorRecord 为 ? GetIterator(value, genKind)。
  6. iteratoriteratorRecord.[[Iterator]]
  7. receivedNormalCompletion(undefined)。
  8. 重复:
    1. 如果 received 是 normal completion,则
      1. innerResult 为 ? Call(iteratorRecord.[[NextMethod]], iteratorRecord.[[Iterator]], « received.[[Value]] »)。
      2. 如果 genKindasync,则将 innerResult 设置为 ? Await(innerResult)。
      3. 如果 innerResult 不是 Object,则抛出 TypeError 异常。
      4. done 为 ? IteratorComplete(innerResult)。
      5. 如果 donetrue,则
        1. 返回 ? IteratorValue(innerResult)。
      6. 如果 genKindasync,则将 received 设置为 Completion(AsyncGeneratorYield(? IteratorValue(innerResult)))。
      7. 否则,将 received 设置为 Completion(GeneratorYield(innerResult))。
    2. 否则如果 received 是 throw completion,则
      1. throw 为 ? GetMethod(iterator, "throw")。
      2. 如果 throw 不是 undefined,则
        1. innerResult 为 ? Call(throw, iterator, « received.[[Value]] »)。
        2. 如果 genKindasync,则将 innerResult 设置为 ? Await(innerResult)。
        3. 注:来自内部迭代器 throw 方法的异常会被传播。来自内部 throw 方法的 normal completion 会以类似于内部 next 的方式处理。
        4. 如果 innerResult 不是 Object,则抛出 TypeError 异常。
        5. done 为 ? IteratorComplete(innerResult)。
        6. 如果 donetrue,则
          1. 返回 ? IteratorValue(innerResult)。
        7. 如果 genKindasync,则将 received 设置为 Completion(AsyncGeneratorYield(? IteratorValue(innerResult)))。
        8. 否则,将 received 设置为 Completion(GeneratorYield(innerResult))。
      3. 否则,
        1. 注:如果 iterator 没有 throw 方法,这个 throw 将会终止 yield* 循环。但首先我们需要给 iterator 一个清理的机会。
        2. closeCompletionNormalCompletion(empty)。
        3. 如果 genKindasync,则执行 ? AsyncIteratorClose(iteratorRecord, closeCompletion)。
        4. 否则,执行 ? IteratorClose(iteratorRecord, closeCompletion)。
        5. 注:下一步会抛出 TypeError,以表明存在 yield* 协议违规:iterator 没有 throw 方法。
        6. 抛出 TypeError 异常。
    3. 否则,
      1. 断言:received 是 return completion。
      2. return 为 ? GetMethod(iterator, "return")。
      3. 如果 returnundefined,则
        1. receivedValuereceived.[[Value]]
        2. 如果 genKindasync,则
          1. receivedValue 设置为 ? Await(receivedValue)。
        3. 返回 ReturnCompletion(receivedValue)。
      4. innerReturnResult 为 ? Call(return, iterator, « received.[[Value]] »)。
      5. 如果 genKindasync,则将 innerReturnResult 设置为 ? Await(innerReturnResult)。
      6. 如果 innerReturnResult 不是 Object,则抛出 TypeError 异常。
      7. done 为 ? IteratorComplete(innerReturnResult)。
      8. 如果 donetrue,则
        1. returnedValue 为 ? IteratorValue(innerReturnResult)。
        2. 返回 ReturnCompletion(returnedValue)。
      9. 如果 genKindasync,则将 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

与 AsyncGenerators 相关的抽象操作定义在 27.9.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 funcObj (an ECMAScript function object) and argList (a List of ECMAScript language values) and returns a throw completion or a return completion. It is defined piecewise over the following productions:

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

15.6.3 Runtime Semantics: InstantiateAsyncGeneratorFunctionObject

The syntax-directed operation InstantiateAsyncGeneratorFunctionObject takes arguments envRecord (an Environment Record) and privateEnv (a PrivateEnvironment Record or null) and returns an ECMAScript function object. It is defined piecewise over the following productions:

AsyncGeneratorDeclaration : async function * BindingIdentifier ( FormalParameters ) { AsyncGeneratorBody }
  1. nameBindingIdentifierStringValue
  2. sourceText 为由 AsyncGeneratorDeclaration 匹配的源文本
  3. closureOrdinaryFunctionCreate(%AsyncGeneratorFunction.prototype%, sourceText, FormalParameters, AsyncGeneratorBody, non-lexical-this, envRecord, privateEnv)。
  4. 执行 SetFunctionName(closure, name)。
  5. protoOrdinaryObjectCreate(%AsyncGeneratorPrototype%)。
  6. 执行 ! DefinePropertyOrThrow(closure, "prototype", PropertyDescriptor { [[Value]]: proto, [[Writable]]: true, [[Enumerable]]: false, [[Configurable]]: false })。
  7. 返回 closure
AsyncGeneratorDeclaration : async function * ( FormalParameters ) { AsyncGeneratorBody }
  1. sourceText 为由 AsyncGeneratorDeclaration 匹配的源文本
  2. closureOrdinaryFunctionCreate(%AsyncGeneratorFunction.prototype%, sourceText, FormalParameters, AsyncGeneratorBody, non-lexical-this, envRecord, privateEnv)。
  3. 执行 SetFunctionName(closure, "default")。
  4. protoOrdinaryObjectCreate(%AsyncGeneratorPrototype%)。
  5. 执行 ! DefinePropertyOrThrow(closure, "prototype", PropertyDescriptor { [[Value]]: proto, [[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 (a property key or a Private Name) and returns an ECMAScript function object. It is defined piecewise over the following productions:

AsyncGeneratorExpression : async function * ( FormalParameters ) { AsyncGeneratorBody }
  1. 如果 name 不存在,则将 name 设置为空 String。
  2. envRecord 为运行中的执行上下文的 LexicalEnvironment。
  3. privateEnv 为运行中的执行上下文的 PrivateEnvironment。
  4. sourceText 为由 AsyncGeneratorExpression 匹配的源文本
  5. closureOrdinaryFunctionCreate(%AsyncGeneratorFunction.prototype%, sourceText, FormalParameters, AsyncGeneratorBody, non-lexical-this, envRecord, privateEnv)。
  6. 执行 SetFunctionName(closure, name)。
  7. protoOrdinaryObjectCreate(%AsyncGeneratorPrototype%)。
  8. 执行 ! DefinePropertyOrThrow(closure, "prototype", PropertyDescriptor { [[Value]]: proto, [[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. sourceText 为由 AsyncGeneratorExpression 匹配的源文本
  8. closureOrdinaryFunctionCreate(%AsyncGeneratorFunction.prototype%, sourceText, FormalParameters, AsyncGeneratorBody, non-lexical-this, funcEnv, privateEnv)。
  9. 执行 SetFunctionName(closure, name)。
  10. protoOrdinaryObjectCreate(%AsyncGeneratorPrototype%)。
  11. 执行 ! DefinePropertyOrThrow(closure, "prototype", PropertyDescriptor { [[Value]]: proto, [[Writable]]: true, [[Enumerable]]: false, [[Configurable]]: false })。
  12. 执行 ! funcEnv.InitializeBinding(name, closure)。
  13. 返回 closure
Note

AsyncGeneratorExpression 中的 BindingIdentifier 可以从该 AsyncGeneratorExpressionAsyncGeneratorBody 内部引用,以允许生成器代码递归调用自身。不过,不同于 AsyncGeneratorDeclarationAsyncGeneratorExpression 中的 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-method, non-constructor-method, or empty. 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 a ClassElement Parse Node or 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 a Boolean. 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 a List of ClassElement Parse Nodes. 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 a List of property keys. It is defined piecewise over the following productions:

ClassElementList : ClassElement
  1. propertyNameClassElementPropName
  2. 如果 propertyNameempty,则返回新的空 List
  3. 如果 ClassElementIsStatictrue,则返回新的空 List
  4. 返回 « propertyName »。
ClassElementList : ClassElementList ClassElement
  1. listClassElementListPrototypePropertyNameList
  2. propertyNameClassElementPropName
  3. 如果 propertyNameempty,则返回 list
  4. 如果 ClassElementIsStatictrue,则返回 list
  5. 返回 list 和 « propertyName » 的列表连接

15.7.7 Static Semantics: AllPrivateIdentifiersValid

The syntax-directed operation AllPrivateIdentifiersValid takes argument names (a List of Strings) and returns a Boolean.

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

  1. 对此 Parse Node 的每个子节点 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 a List of Strings. 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 a Boolean.

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

  1. 对此 Parse Node 的每个子节点 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 homeObj (an Object) and returns either a normal completion containing a ClassFieldDefinition Record or an abrupt completion. It is defined piecewise over the following productions:

FieldDefinition : ClassElementName Initializeropt
  1. name 为 ? ClassElementNameEvaluation
  2. 如果存在 Initializer,则
    1. formalParamList 为产生式 FormalParameters : [empty] 的实例。
    2. envRecord 为运行中的执行上下文的 LexicalEnvironment。
    3. privateEnv 为运行中的执行上下文的 PrivateEnvironment。
    4. sourceText 为空的 Unicode 码点序列。
    5. initializerOrdinaryFunctionCreate(%Function.prototype%, sourceText, formalParamList, Initializer, non-lexical-this, envRecord, privateEnv)。
    6. 执行 MakeMethod(initializer, homeObj)。
    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 homeObj (an Object) and returns a ClassStaticBlockDefinition Record. It is defined piecewise over the following productions:

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

15.7.12 Runtime Semantics: EvaluateClassStaticBlockBody

The syntax-directed operation EvaluateClassStaticBlockBody takes argument funcObj (an ECMAScript function object) and returns a return completion or a throw completion. It is defined piecewise over the following productions:

ClassStaticBlockBody : ClassStaticBlockStatementList
  1. 断言:funcObj 是由 ClassStaticBlockDefinitionEvaluation 步骤 5 创建的合成函数。
  2. 执行 ! FunctionDeclarationInstantiation(funcObj, « »)。
  3. resultClassStaticBlockStatementList 的求值的 Completion
  4. envRecord 为运行中执行上下文的 LexicalEnvironment。
  5. 断言:envRecord 是声明式环境记录。
  6. 执行 ? DisposeResources(envRecord.[[DisposableResourceStack]], result)。
  7. 返回 ReturnCompletion(undefined)。

15.7.13 Runtime Semantics: ClassElementEvaluation

The syntax-directed operation ClassElementEvaluation takes argument obj (an Object) and returns either a normal completion containing either a ClassFieldDefinition Record, a ClassStaticBlockDefinition Record, a PrivateElement, or unused, or an abrupt completion. It is defined piecewise over the following productions:

ClassElement : FieldDefinition ; static FieldDefinition ;
  1. 返回 ? 以 obj 为实参执行 FieldDefinitionClassFieldDefinitionEvaluation
ClassElement : MethodDefinition static MethodDefinition
  1. 返回 ? 以 objfalse 为实参执行 MethodDefinitionMethodDefinitionEvaluation
ClassElement : ClassStaticBlock
  1. 返回以 obj 为实参执行 ClassStaticBlockClassStaticBlockDefinitionEvaluation
ClassElement : ;
  1. 返回 unused

15.7.14 Runtime Semantics: ClassDefinitionEvaluation

The syntax-directed operation ClassDefinitionEvaluation takes arguments classBinding (a String or undefined), className (a property key or a Private Name), and sourceText (ECMAScript source text) and returns either a normal completion containing a function object or an abrupt completion.

Note

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

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

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

It is defined piecewise over the following productions:

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

15.7.15 Runtime Semantics: BindingClassDeclarationEvaluation

The syntax-directed operation BindingClassDeclarationEvaluation takes no arguments and returns either a normal completion containing a function object or an abrupt completion. It is defined piecewise over the following productions:

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

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

15.7.16 Runtime Semantics: Evaluation

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

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

ClassExpression : class ClassTail
  1. sourceText 为由 ClassExpression 匹配的源文本
  2. 返回 ? 以 undefined、空 String 和 sourceText 为实参执行 ClassTailClassDefinitionEvaluation
ClassExpression : class BindingIdentifier ClassTail
  1. classNameBindingIdentifierStringValue
  2. sourceText 为由 ClassExpression 匹配的源文本
  3. 返回 ? 以 classNameclassNamesourceText 为实参执行 ClassTailClassDefinitionEvaluation
ClassElementName : PrivateIdentifier
  1. privateIdentifierPrivateIdentifierStringValue
  2. privateEnvRecord 为运行中的执行上下文的 PrivateEnvironment。
  3. namesprivateEnvRecord.[[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 envRecord (an Environment Record) and privateEnv (a PrivateEnvironment Record or null) and returns an ECMAScript function object. It is defined piecewise over the following productions:

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

15.8.3 Runtime Semantics: InstantiateAsyncFunctionExpression

The syntax-directed operation InstantiateAsyncFunctionExpression takes optional argument name (a property key or a Private Name) and returns an ECMAScript function object. It is defined piecewise over the following productions:

AsyncFunctionExpression : async function ( FormalParameters ) { AsyncFunctionBody }
  1. 如果 name 不存在,则将 name 设置为空 String。
  2. envRecord 为运行中的执行上下文的 LexicalEnvironment。
  3. privateEnv 为运行中的执行上下文的 PrivateEnvironment。
  4. sourceText 为由 AsyncFunctionExpression 匹配的源文本
  5. closureOrdinaryFunctionCreate(%AsyncFunction.prototype%, sourceText, FormalParameters, AsyncFunctionBody, non-lexical-this, envRecord, 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. sourceText 为由 AsyncFunctionExpression 匹配的源文本
  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 内部引用,以允许函数递归调用自身。不过,不同于 FunctionDeclarationAsyncFunctionExpression 中的 BindingIdentifier 不能从包围该 AsyncFunctionExpression 的作用域中引用,也不会影响该作用域。

15.8.4 Runtime Semantics: EvaluateAsyncFunctionBody

The syntax-directed operation EvaluateAsyncFunctionBody takes arguments funcObj (an ECMAScript function object) and argList (a List of ECMAScript language values) and returns a return completion. It is defined piecewise over the following productions:

AsyncFunctionBody : FunctionBody
  1. promiseCapability 为 ! NewPromiseCapability(%Promise%)。
  2. completionCompletion(FunctionDeclarationInstantiation(funcObj, argList))。
  3. 如果 completion 是 abrupt 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
UnaryExpression : CoverAwaitExpressionAndAwaitUsingDeclarationHead
  1. exprCoverAwaitExpressionAndAwaitUsingDeclarationHead覆盖的 AwaitExpression
  2. 返回 expr 的 ? Evaluation
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 a Boolean. 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 funcObj (an ECMAScript function object) and argList (a List of ECMAScript language values) and returns a return completion. It is defined piecewise over the following productions:

AsyncConciseBody : ExpressionBody
  1. promiseCapability 为 ! NewPromiseCapability(%Promise%)。
  2. completionCompletion(FunctionDeclarationInstantiation(funcObj, argList))。
  3. 如果 completion 是 abrupt 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 (a property key or a Private Name) and returns an ECMAScript function object. It is defined piecewise over the following productions:

AsyncArrowFunction : async AsyncArrowBindingIdentifier => AsyncConciseBody
  1. 如果 name 不存在,则将 name 设置为空 String。
  2. envRecord 为运行中的执行上下文的 LexicalEnvironment。
  3. privateEnv 为运行中的执行上下文的 PrivateEnvironment。
  4. sourceText 为由 AsyncArrowFunction 匹配的源文本
  5. paramsAsyncArrowBindingIdentifier
  6. closureOrdinaryFunctionCreate(%AsyncFunction.prototype%, sourceText, params, AsyncConciseBody, lexical-this, envRecord, privateEnv)。
  7. 执行 SetFunctionName(closure, name)。
  8. 返回 closure
AsyncArrowFunction : CoverCallExpressionAndAsyncArrowHead => AsyncConciseBody
  1. 如果 name 不存在,则将 name 设置为空 String。
  2. envRecord 为运行中的执行上下文的 LexicalEnvironment。
  3. privateEnv 为运行中的执行上下文的 PrivateEnvironment。
  4. sourceText 为由 AsyncArrowFunction 匹配的源文本
  5. head 为由 CoverCallExpressionAndAsyncArrowHead 覆盖的 AsyncArrowHead
  6. paramsheadArrowFormalParameters
  7. closureOrdinaryFunctionCreate(%AsyncFunction.prototype%, sourceText, params, AsyncConciseBody, lexical-this, envRecord, 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 (a CallExpression Parse Node, a MemberExpression Parse Node, or an OptionalChain Parse Node) and returns a Boolean. 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 (a CallExpression Parse Node, a MemberExpression Parse Node, or an OptionalChain Parse Node) and returns a Boolean.

Note 1

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

Note 2

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

Note 3

在同一个 BlockForStatementForInOfStatementFunctionBodyGeneratorBodyAsyncGeneratorBodyAsyncFunctionBodyClassStaticBlockBody 中,位于某个调用之前的 using 声明或 await using 声明会阻止该调用成为可能的尾位置调用。

It is defined piecewise over the following productions:

StatementList : StatementList StatementListItem
  1. has 为以 call 为参数的派生 StatementListHasCallInTailPosition
  2. 如果 hastrue,则返回 true
  3. 如果派生 StatementListContainsUsingtrue,则返回 false
  4. 返回以 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 CoverAwaitExpressionAndAwaitUsingDeclarationHead 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. expr 为由 CoverParenthesizedExpressionAndArrowParameterList 覆盖的 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

例如,尾位置调用使实现的激活记录栈增长的量,应仅为目标函数激活记录大小超出调用函数激活记录大小的部分。如果目标函数的激活记录更小,则栈的总大小应减少。