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. - is designed to be subclassable. It may be used as the value of an
extends
clause of a class definition. Subclass constructors 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 defining function 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 ( p1, p2, … , pn, body )
The last argument specifies the body (executable code) of a function; any preceding arguments specify formal parameters.
When the Function
function is called with some arguments p1, p2, … , pn, body (where n might be 0, that is, there are no “ p ” arguments, and where body might also not be provided), the following steps are taken:
- Let C be the
active function object . - Let args be the argumentsList that was passed to this function by [[Call]] or [[Construct]].
- Return ?
CreateDynamicFunction (C, NewTarget,normal , args).
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, args )
The abstract operation CreateDynamicFunction takes arguments constructor (a new
was initially applied to. args is the argument values that were passed to constructor. It performs the following steps when called:
Assert : Theexecution context stack has at least two elements.- Let callerContext be the second to top element of the
execution context stack . - Let callerRealm be callerContext's
Realm . - Let calleeRealm be
the current Realm Record . - Perform ?
HostEnsureCanCompileStrings (callerRealm, calleeRealm). - If newTarget is
undefined , set newTarget to constructor. - If kind is
normal , then- Let goal be the grammar symbol
FunctionBody .[~Yield, ~Await] - Let parameterGoal be the grammar symbol
FormalParameters .[~Yield, ~Await] - Let fallbackProto be
"%Function.prototype%" .
- Let goal be the grammar symbol
- Else if kind is
generator , then- Let goal be the grammar symbol
GeneratorBody . - Let parameterGoal be the grammar symbol
FormalParameters .[+Yield, ~Await] - Let fallbackProto be
"%GeneratorFunction.prototype%" .
- Let goal be the grammar symbol
- Else if kind is
async , then- Let goal be the grammar symbol
AsyncFunctionBody . - Let parameterGoal be the grammar symbol
FormalParameters .[~Yield, +Await] - Let fallbackProto be
"%AsyncFunction.prototype%" .
- Let goal be the grammar symbol
- Else,
Assert : kind isasyncGenerator .- Let goal be the grammar symbol
AsyncGeneratorBody . - Let parameterGoal be the grammar symbol
FormalParameters .[+Yield, +Await] - Let fallbackProto be
"%AsyncGeneratorFunction.prototype%" .
- Let argCount be the number of elements in args.
- Let P be the empty String.
- If argCount = 0, let bodyArg be the empty String.
- Else if argCount = 1, let bodyArg be args[0].
- Else,
Assert : argCount > 1.- Let firstArg be args[0].
- Set P to ?
ToString (firstArg). - Let k be 1.
- Repeat, while k < argCount - 1,
- Let nextArg be args[k].
- Let nextArgString be ?
ToString (nextArg). - Set P to the
string-concatenation of P,"," (a comma), and nextArgString. - Set k to k + 1.
- Let bodyArg be args[k].
- Let bodyString be the
string-concatenation of 0x000A (LINE FEED), ?ToString (bodyArg), and 0x000A (LINE FEED). - Let prefix be the prefix associated with kind in
Table 50 . - Let sourceString be the
string-concatenation of prefix," anonymous(" , P, 0x000A (LINE FEED),") {" , bodyString, and"}" . - Let sourceText be !
StringToCodePoints (sourceString). - Perform the following substeps in an
implementation-defined order, possibly interleaving parsing and error detection:- Let parameters be
ParseText (!StringToCodePoints (P), parameterGoal). - If parameters is a
List of errors, throw aSyntaxError exception. - Let body be
ParseText (!StringToCodePoints (bodyString), goal). - If body is a
List of errors, throw aSyntaxError exception. - Let strict be
FunctionBodyContainsUseStrict of body. - If strict is
true , apply theearly error rules for to parameters.UniqueFormalParameters : FormalParameters - If strict is
true andIsSimpleParameterList of parameters isfalse , throw aSyntaxError exception. - If any element of the
BoundNames of parameters also occurs in theLexicallyDeclaredNames of body, throw aSyntaxError exception. - If body
Contains SuperCall istrue , throw aSyntaxError exception. - If parameters
Contains SuperCall istrue , throw aSyntaxError exception. - If body
Contains SuperProperty istrue , throw aSyntaxError exception. - If parameters
Contains SuperProperty istrue , throw aSyntaxError exception. - If kind is
generator orasyncGenerator , then- If parameters
Contains YieldExpression istrue , throw aSyntaxError exception.
- If parameters
- If kind is
async orasyncGenerator , then- If parameters
Contains AwaitExpression istrue , throw aSyntaxError exception.
- If parameters
- If strict is
true , then- If
BoundNames of parameters contains any duplicate elements, throw aSyntaxError exception.
- If
- Let parameters be
- Let proto be ?
GetPrototypeFromConstructor (newTarget, fallbackProto). - Let realmF be
the current Realm Record . - Let scope be realmF.[[GlobalEnv]].
- Let F be !
OrdinaryFunctionCreate (proto, sourceText, parameters, body,non-lexical-this , scope). - 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
asyncGenerator , 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 , performMakeConstructor (F). - 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
Kind | Prefix |
---|---|
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 the following properties:
20.2.2.1 Function.length
This is a
20.2.2.2 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 )
When the apply
method is called with arguments thisArg and argArray, the following steps are taken:
- Let func be the
this value. - If
IsCallable (func) isfalse , throw aTypeError exception. - If argArray is
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 an arrow function or a
20.2.3.2 Function.prototype.bind ( thisArg, ...args )
When the bind
method is called with argument thisArg and zero or more args, it performs the following steps:
- 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
Type (targetLen) is Number, then- If targetLen is
+∞ 𝔽, set L to +∞. - Else if targetLen is
-∞ 𝔽, set L to 0. - Else,
- Let targetLenAsInt be !
ToIntegerOrInfinity (targetLen). Assert : targetLenAsInt is finite.- 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
Type (targetName) is not String, set targetName to the empty String. - Perform
SetFunctionName (F, targetName,"bound" ). - Return F.
Function objects created using Function.prototype.bind
are exotic objects. They also do not have a
If Target is an arrow function or a
20.2.3.3 Function.prototype.call ( thisArg, ...args )
When the call
method is called with argument thisArg and zero or more args, the following steps are taken:
- 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 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 ( )
When the toString
method is called, the following steps are taken:
- Let func be the
this value. - If
Type (func) is Object and func has a [[SourceText]] internal slot and func.[[SourceText]] is a sequence of Unicode code points and !HostHasSourceTextAvailable (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
Type (func) is 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 )
When the @@hasInstance
method of an object F is called with value V, the following steps are taken:
- Let F be the
this value. - Return ?
OrdinaryHasInstance (F, V).
The value of the
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.
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 objects created using Function.prototype.bind
, or by evaluating a
20.2.5 HostHasSourceTextAvailable ( func )
The
An implementation of HostHasSourceTextAvailable must complete normally in all cases. This operation 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 completion record. The default implementation of HostHasSourceTextAvailable is to unconditionally return a normal completion with a value of