20.2 Function Objects
20.2.1 The Function Constructor
The Function
- is %Function%.
- is the initial value of the
"Function" property of theglobal object . - creates and initializes a new
function object when called as a function rather than as aconstructor . Thus the function callFunction(…)
is equivalent to the object creation expressionnew Function(…)
with the same arguments. - may be used as the value of an
extends
clause of a class definition. Subclassconstructors that intend to inherit the specified Function behaviour must include asuper
call to the Functionconstructor to create and initialize a subclass instance with the internal slots necessary for built-in function behaviour. All ECMAScript syntactic forms for definingfunction objects create instances of Function. There is no syntactic means to create instances of Function subclasses except for the built-in GeneratorFunction, AsyncFunction, and AsyncGeneratorFunction subclasses.
20.2.1.1 Function ( ...parameterArgs, bodyArg )
The last argument (if any) specifies the body (executable code) of a function; any preceding arguments specify formal parameters.
This function performs the following steps when called:
- Let C be the
active function object . - If bodyArg is not present, set bodyArg to the empty String.
- Return ?
CreateDynamicFunction (C, NewTarget,normal , parameterArgs, bodyArg).
It is permissible but not necessary to have one argument for each formal parameter to be specified. For example, all three of the following expressions produce the same result:
new Function("a", "b", "c", "return a+b+c")
new Function("a, b, c", "return a+b+c")
new Function("a,b", "c", "return a+b+c")
20.2.1.1.1 CreateDynamicFunction ( constructor, newTarget, kind, parameterArgs, bodyArg )
The abstract operation CreateDynamicFunction takes arguments constructor (a new
was initially applied to. parameterArgs and bodyArg reflect the argument values that were passed to constructor. It performs the following steps when called:
- If newTarget is
undefined , set newTarget to constructor. - If kind is
normal , then- Let prefix be
"function" . - Let exprSym be the grammar symbol
FunctionExpression . - Let bodySym be the grammar symbol
FunctionBody .[~Yield, ~Await] - Let parameterSym be the grammar symbol
FormalParameters .[~Yield, ~Await] - Let fallbackProto be
"%Function.prototype%" .
- Let prefix be
- Else if kind is
generator , then- Let prefix be
"function*" . - Let exprSym be the grammar symbol
GeneratorExpression . - Let bodySym be the grammar symbol
GeneratorBody . - Let parameterSym be the grammar symbol
FormalParameters .[+Yield, ~Await] - Let fallbackProto be
"%GeneratorFunction.prototype%" .
- Let prefix be
- Else if kind is
async , then- Let prefix be
"async function" . - Let exprSym be the grammar symbol
AsyncFunctionExpression . - Let bodySym be the grammar symbol
AsyncFunctionBody . - Let parameterSym be the grammar symbol
FormalParameters .[~Yield, +Await] - Let fallbackProto be
"%AsyncFunction.prototype%" .
- Let prefix be
- Else,
Assert : kind isasync-generator .- Let prefix be
"async function*" . - Let exprSym be the grammar symbol
AsyncGeneratorExpression . - Let bodySym be the grammar symbol
AsyncGeneratorBody . - Let parameterSym be the grammar symbol
FormalParameters .[+Yield, +Await] - Let fallbackProto be
"%AsyncGeneratorFunction.prototype%" .
- Let argCount be the number of elements in parameterArgs.
- Let bodyString be ?
ToString (bodyArg). - Let parameterStrings be a new empty
List . - For each element arg of parameterArgs, do
- Append ?
ToString (arg) to parameterStrings.
- Append ?
- Let currentRealm be
the current Realm Record . - Perform ?
HostEnsureCanCompileStrings (currentRealm, parameterStrings, bodyString,false ). - Let P be the empty String.
- If argCount > 0, then
- Set P to parameterStrings[0].
- Let k be 1.
- Repeat, while k < argCount,
- Let nextArgString be parameterStrings[k].
- Set P to the
string-concatenation of P,"," (a comma), and nextArgString. - Set k to k + 1.
- Let bodyParseString be the
string-concatenation of 0x000A (LINE FEED), bodyString, and 0x000A (LINE FEED). - Let sourceString be the
string-concatenation of prefix," anonymous(" , P, 0x000A (LINE FEED),") {" , bodyParseString, and"}" . - Let sourceText be
StringToCodePoints (sourceString). - Let parameters be
ParseText (StringToCodePoints (P), parameterSym). - If parameters is a
List of errors, throw aSyntaxError exception. - Let body be
ParseText (StringToCodePoints (bodyParseString), bodySym). - If body is a
List of errors, throw aSyntaxError exception. - NOTE: The parameters and body are parsed separately to ensure that each is valid alone. For example,
new Function("/*", "*/ ) {")
does not evaluate to a function. - NOTE: If this step is reached, sourceText must have the syntax of exprSym (although the reverse implication does not hold). The purpose of the next two steps is to enforce any Early Error rules which apply to exprSym directly.
- Let expr be
ParseText (sourceText, exprSym). - If expr is a
List of errors, throw aSyntaxError exception. - Let proto be ?
GetPrototypeFromConstructor (newTarget, fallbackProto). - Let env be currentRealm.[[GlobalEnv]].
- Let privateEnv be
null . - Let F be
OrdinaryFunctionCreate (proto, sourceText, parameters, body,non-lexical-this , env, privateEnv). - Perform
SetFunctionName (F,"anonymous" ). - If kind is
generator , then- Let prototype be
OrdinaryObjectCreate (%GeneratorFunction.prototype.prototype% ). - Perform !
DefinePropertyOrThrow (F,"prototype" , PropertyDescriptor { [[Value]]: prototype, [[Writable]]:true , [[Enumerable]]:false , [[Configurable]]:false }).
- Let prototype be
- Else if kind is
async-generator , then- Let prototype be
OrdinaryObjectCreate (%AsyncGeneratorFunction.prototype.prototype% ). - Perform !
DefinePropertyOrThrow (F,"prototype" , PropertyDescriptor { [[Value]]: prototype, [[Writable]]:true , [[Enumerable]]:false , [[Configurable]]:false }).
- Let prototype be
- Else if kind is
normal , then- Perform
MakeConstructor (F).
- Perform
- NOTE: Functions whose kind is
async are not constructible and do not have a [[Construct]] internal method or a"prototype" property. - Return F.
CreateDynamicFunction defines a
20.2.2 Properties of the Function Constructor
The Function
- is itself a built-in
function object . - has a [[Prototype]] internal slot whose value is
%Function.prototype% . - has a
"length" property whose value is1 𝔽. - has the following properties:
20.2.2.1 Function.prototype
The value of Function.prototype
is the
This property has the attributes { [[Writable]]:
20.2.3 Properties of the Function Prototype Object
The Function prototype object:
- is %Function.prototype%.
- is itself a built-in
function object . - accepts any arguments and returns
undefined when invoked. - does not have a [[Construct]] internal method; it cannot be used as a
constructor with thenew
operator. - has a [[Prototype]] internal slot whose value is
%Object.prototype% . - does not have a
"prototype" property. - has a
"length" property whose value is+0 𝔽. - has a
"name" property whose value is the empty String.
The Function prototype object is specified to be a
20.2.3.1 Function.prototype.apply ( thisArg, argArray )
This method performs the following steps when called:
- Let func be the
this value. - If
IsCallable (func) isfalse , throw aTypeError exception. - If argArray is either
undefined ornull , then- Perform
PrepareForTailCall (). - Return ?
Call (func, thisArg).
- Perform
- Let argList be ?
CreateListFromArrayLike (argArray). - Perform
PrepareForTailCall (). - Return ?
Call (func, thisArg, argList).
The thisArg value is passed without modification as the
If func is either an arrow function or a
20.2.3.2 Function.prototype.bind ( thisArg, ...args )
This method performs the following steps when called:
- Let Target be the
this value. - If
IsCallable (Target) isfalse , throw aTypeError exception. - Let F be ?
BoundFunctionCreate (Target, thisArg, args). - Let L be 0.
- Let targetHasLength be ?
HasOwnProperty (Target,"length" ). - If targetHasLength is
true , then- Let targetLen be ?
Get (Target,"length" ). - If targetLen
is a Number , then- If targetLen is
+∞ 𝔽, then- Set L to +∞.
- Else if targetLen is
-∞ 𝔽, then- Set L to 0.
- Else,
- Let targetLenAsInt be !
ToIntegerOrInfinity (targetLen). Assert : targetLenAsInt isfinite .- Let argCount be the number of elements in args.
- Set L to
max (targetLenAsInt - argCount, 0).
- Let targetLenAsInt be !
- If targetLen is
- Let targetLen be ?
- Perform
SetFunctionLength (F, L). - Let targetName be ?
Get (Target,"name" ). - If targetName
is not a String , set targetName to the empty String. - Perform
SetFunctionName (F, targetName,"bound" ). - Return F.
Function.prototype.bind
are
If Target is either an arrow function or a
20.2.3.3 Function.prototype.call ( thisArg, ...args )
This method performs the following steps when called:
- Let func be the
this value. - If
IsCallable (func) isfalse , throw aTypeError exception. - Perform
PrepareForTailCall (). - Return ?
Call (func, thisArg, args).
The thisArg value is passed without modification as the
If func is either an arrow function or a
20.2.3.4 Function.prototype.constructor
The initial value of Function.prototype.constructor
is
20.2.3.5 Function.prototype.toString ( )
This method performs the following steps when called:
- Let func be the
this value. - If func
is an Object , func has a [[SourceText]] internal slot, func.[[SourceText]] is a sequence of Unicode code points, andHostHasSourceTextAvailable (func) istrue , then- Return
CodePointsToString (func.[[SourceText]]).
- Return
- If func is a
built-in function object , return animplementation-defined String source code representation of func. The representation must have the syntax of aNativeFunction . Additionally, if func has an [[InitialName]] internal slot and func.[[InitialName]]is a String , the portion of the returned String that would be matched byNativeFunctionAccessor opt PropertyName must be the value of func.[[InitialName]]. - If func
is an Object andIsCallable (func) istrue , return animplementation-defined String source code representation of func. The representation must have the syntax of aNativeFunction . - Throw a
TypeError exception.
20.2.3.6 Function.prototype [ @@hasInstance ] ( V )
This method performs the following steps when called:
- Let F be the
this value. - Return ?
OrdinaryHasInstance (F, V).
This property has the attributes { [[Writable]]:
This is the default implementation of @@hasInstance
that most functions inherit. @@hasInstance
is called by the instanceof
operator to determine whether a value is an instance of a specific
v instanceof F
evaluates as
F[@@hasInstance](v)
A instanceof
by exposing a different @@hasInstance
method on the function.
This property is non-writable and non-configurable to prevent tampering that could be used to globally expose the target function of a bound function.
The value of the
20.2.4 Function Instances
Every Function instance is an ECMAScript Function.prototype.bind
method (
Function instances have the following properties:
20.2.4.1 length
The value of the
20.2.4.2 name
The value of the
Anonymous functions objects that do not have a contextual name associated with them by this specification use the empty String as the value of the
20.2.4.3 prototype
Function instances that can be used as a
This property has the attributes { [[Writable]]:
Function.prototype.bind
, or by evaluating a
20.2.5 HostHasSourceTextAvailable ( func )
The
An implementation of HostHasSourceTextAvailable must conform to the following requirements:
- It must be deterministic with respect to its parameters. Each time it is called with a specific func as its argument, it must return the same result.
The default implementation of HostHasSourceTextAvailable is to return