1.Introduction
This section is informative.
Technical reports published by the W3C that include programminglanguage interfaces have typically been described using theObject Management Group’s Interface Definition Language (IDL)[OMGIDL]. The IDL provides a means todescribe these interfaces in a language independent manner. Usually,additional language binding appendices are included in suchdocuments which detail how the interfaces described with the IDLcorrespond to constructs in the given language.
However, the bindings in these specifications for the language mostcommonly used on the web, ECMAScript, are consistently specified withlow enough precision as to result in interoperability issues. Inaddition, each specification must describe the same basic information,such as DOM interfaces described in IDL corresponding to propertieson the ECMAScript global object, or theunsigned long IDL type mapping to the Numbertype in ECMAScript.
This specification defines an IDL language similar to OMG IDLfor use by specifications that define interfaces for Web APIs. A number of extensions aregiven to the IDL to support common functionality that previously musthave been written in prose. In addition, precise language bindingsfor the ECMAScript language are given.
2.Interface definition language
This section describes a language,Web IDL, which can be used to defineinterfaces for APIs in the Web platform. A specification that defines Web APIscan include one or moreIDL fragments thatdescribe the interfaces (the state and behavior that objects can exhibit)for the APIs defined by that specification.AnIDL fragment isa sequence of definitions that matches the
The different kinds ofdefinitions that can appear in anIDL fragment are:interfaces,partial interface definitions,interface mixins,partial mixin definitions,callback functions,callback interfaces,namespaces,partial namespace definitions,dictionaries,partial dictionary definitions,typedefs andincludes statements.These are all defined in the following sections.
Eachdefinition (matching
[extended_attributes ]interface identifier { /* interface_members... */};
Definitions ::ExtendedAttributeList Definition Definitions ε
Definition ::CallbackOrInterfaceOrMixin Namespace Partial Dictionary Enum Typedef IncludesStatement
The following is an example of anIDL fragment.
[Exposed =Window ]interface Paint { };[Exposed =Window ]interface SolidColor :Paint {attribute double red ;attribute double green ;attribute double blue ;};[Exposed =Window ]interface Pattern :Paint {attribute DOMString imageURL ;};[Exposed =Window ]interface GraphicalWindow {constructor ();readonly attribute unsigned long width ;readonly attribute unsigned long height ;attribute Paint currentPaint ;void drawRectangle (double x ,double y ,double width ,double height );void drawText (double x ,double y ,DOMString text );};
Here, fourinterfaces are being defined. TheGraphicalWindow interface has tworead onlyattributes, one writable attribute, and twooperations defined on it. Objects that implement theGraphicalWindow interface will expose these attributes and operations in a manner appropriate to the particular language being used.
In ECMAScript, the attributes on the IDL interfaces will be exposed as accessor properties and the operations as data properties whose value is abuilt-in function object on a prototype object for allGraphicalWindow objects; each ECMAScript object that implementsGraphicalWindow will have that prototype object in its prototype chain.
Theconstructor operation that appears onGraphicalWindow causes aconstructor to exist in ECMAScript implementations, so that callingnew GraphicalWindow() would return a new object that implemented the interface.
Allinterfaces have the [Exposed]extended attribute, which ensures the interfaces are only available inRealms whoseglobal object is aWindow object.
2.1.Names
Everyinterface,partial interface definition,namespace,partial namespace definition,dictionary,partial dictionary definition,enumeration,callback function,callback interface andtypedef (together callednamed definitions)and everyconstant,attribute,anddictionary member has anidentifier, as do someoperations.The identifier is determined by an
Fornamed definitions,the
identifier token that appearsdirectly after theinterface ,namespace ,dictionary ,enum orcallback keyworddetermines the identifier of that definition.interface interface_identifier { /* interface_members... */ };partial interface interface_identifier { /* interface_members... */ };namespace namespace_identifier { /* namespace_members... */ };partial namespace namespace_identifier { /* namespace_members... */ };dictionary dictionary_identifier { /* dictionary_members... */ };partial dictionary dictionary_identifier { /* dictionary_members... */ };enum enumeration_identifier {"enum" ,"values" /* , ... */ };callback callback_identifier =return_type (/* arguments... */);callback interface callback_interface_identifier { /* interface_members... */ };Forattributes,typedefs anddictionary members,the final
identifier token before thesemicolon at the end of the declaration determines the identifier.[
extended_attributes ]interface identifier {attribute type attribute_identifier ;};typedef type typedef_identifier ;dictionary identifier {type dictionary_member_identifier ;};Forconstants,the
identifier token before theequals sign determines the identifier.const type constant_identifier = 42;Foroperations, the
identifier token that appearsafter the return type but before the opening parenthesis (that is,one that is matched as part of theOptionalOperationName grammar symbol in anOperationRest ) determines the identifier of the operation. Ifthere is no suchidentifier token,then the operation does not have an identifier.interface interface_identifier {return_type operation_identifier (/* arguments... */);};
Note: Operations can have no identifier when they are being used to declare aspecial kind of operation, such as a getter or setter.
For all of these constructs, theidentifier is the value of the
Note: A leading"_" is used to escape an identifier from lookinglike a reserved word so that, for example, an interface named "interface" can bedefined. The leading"_" is dropped to unescape theidentifier.
Operation arguments can take a slightly wider set of identifiers. In an operationdeclaration, the identifier of an argument is specified immediately after itstype and is given by either an
interface interface_identifier {return_type operation_identifier (argument_type argument_identifier /* , ... */);};
ArgumentNameKeyword ::async attribute callback const constructor deleter dictionary enum getter includes inherit interface iterable maplike mixin namespace partial readonly required setlike setter static stringifier typedef unrestricted
If an
Theidentifier of any of the abovementionedIDL constructs (except operation arguments) must not be "constructor","toString",or begin with aU+005F LOW LINE ("_") character. Theseare known asreserved identifiers.
Although the "toJSON"identifier is not areserved identifier,it must only be used forregular operations that convert objects toJSON types,as described in§ 2.5.3.1 toJSON.
Note: Further restrictions on identifier names for particular constructs may be madein later sections.
Within the set ofIDL fragments that a given implementation supports,theidentifier of everyinterface,namespace,dictionary,enumeration,callback function,callback interface andtypedef must notbe the same as the identifier of any otherinterface,namespace,dictionary,enumeration,callback function,callback interface ortypedef.
Within anIDL fragment, a referenceto adefinition need not appear afterthe declaration of the referenced definition. References can also be madeacrossIDL fragments.
Therefore, the followingIDL fragment is valid:
[Exposed =Window ]interface B :A {void f (SequenceOfLongs x );};[Exposed =Window ]interface A {};typedef sequence <long >SequenceOfLongs ;
The followingIDL fragment demonstrates howidentifiers are given to definitions andinterface members.
// Typedef identifier: "number"typedef double number ;// Interface identifier: "System"[Exposed =Window ]interface System { // Operation identifier: "createObject" // Operation argument identifier: "interface"object createObject (DOMString _interface ); // Operation argument identifier: "interface"sequence <object >getObjects (DOMString interface ); // Operation has no identifier; it declares a getter.getter DOMString (DOMString keyName );};// Interface identifier: "TextField"[Exposed =Window ]interface TextField { // Attribute identifier: "const"attribute boolean _const ; // Attribute identifier: "value"attribute DOMString ?_value ;};
Note that while the secondattribute on theTextFieldinterface need not have been escaped with an underscore (because "value" is not a keyword in the IDL grammar), it is still unescaped to obtain the attribute’sidentifier.
2.2.Interfaces
IDL fragments are used todescribe object oriented systems. In such systems, objects are entitiesthat have identity and which are encapsulations of state and behavior.Aninterface is a definition (matching
[extended_attributes ]interface identifier { /* interface_members... */};
An interface is a specification of a set ofinterface members (matching
Interfaces in Web IDL describe how objects that implement theinterface behave. In bindings for object oriented languages, it isexpected that an object that implements a particular IDL interfaceprovides ways to inspect and modify the object’s state and toinvoke the behavior described by the interface.
An interface can be defined toinherit from another interface.If the identifier of the interface is followed by aU+003A COLON (":") characterand anidentifier,then that identifier identifies the inherited interface.An object that implements an interface that inherits from anotheralso implements that inherited interface. The object therefore will alsohave members that correspond to the interface members from the inherited interface.
interface identifier :identifier_of_inherited_interface { /* interface_members... */};
The order that members appear in has significance for property enumeration in theECMAScript binding.
Interfaces may specify an interface member that has the same name asone from an inherited interface. Objects that implement the derivedinterface will expose the member on the derived interface. It islanguage binding specific whether the overridden member can beaccessed on the object.
Consider the following two interfaces.
[Exposed =Window ]interface A {void f ();void g ();};[Exposed =Window ]interface B :A {void f ();void g (DOMString x );};
In the ECMAScript language binding, an instance ofB will have a prototype chain that looks like the following:
[Object.prototype: the Object prototype object] ↑[A.prototype: interface prototype object for A] ↑[B.prototype: interface prototype object for B] ↑[instanceOfB]
CallinginstanceOfB.f() in ECMAScript will invoke the f defined onB. However, the f fromA can still be invoked on an object that implementsB by callingA.prototype.f.call(instanceOfB).
Theinherited interfaces ofa given interfaceA is the set of all interfaces thatA inherits from, directly or indirectly. IfA does notinherit from another interface, then the set is empty. Otherwise, the setincludes the interfaceB thatAinherits from and all ofB’sinherited interfaces.
An interface must not be declared such thatits inheritance hierarchy has a cycle. That is, an interfaceA cannot inherit from itself, nor can it inherit from anotherinterfaceB that inherits fromA, and so on.
Note that general multiple inheritance of interfaces is not supported, andobjects also cannot implement arbitrary sets of interfaces.Objects can be defined to implement a single given interfaceA,which means that it also implements all ofA’sinherited interfaces.In addition, anincludes statement can be usedto define that objects implementing aninterfaceA will always also include themembers of theinterface mixinsAincludes.
Each interface member can be preceded by a list ofextended attributes (matching
[extended_attributes ]interface identifier { [extended_attributes ]const type constant_identifier = 42; [extended_attributes ]attribute type identifier ; [extended_attributes ]return_type identifier (/* arguments... */);};
The IDL for interfaces can be split into multiple parts by usingpartial interface definitions(matching
interface SomeInterface { /* interface_members... */};partial interface SomeInterface { /* interface_members... */};
Note: Partial interface definitions are intended for use as a specificationeditorial aide, allowing the definition of an interface to be separatedover more than one section of the document, and sometimes multiple documents.
The order of appearance of aninterface definition and any of itspartial interface definitions does not matter.
Note: A partial interface definition cannot specify that the interfaceinherits from another interface.Inheritance must be specified on the originalinterface definition.
The relevant language binding determines how interfaces correspond to constructsin the language.
The following extended attributes are applicable to interfaces:[Exposed],[Global],[LegacyWindowAlias],[NamedConstructor],[NoInterfaceObject],[OverrideBuiltins], and[SecureContext].
The following extended attributes are applicable topartial interfaces:[Exposed],[OverrideBuiltins], and[SecureContext].
Interfaces which are not annotatedwith a [NoInterfaceObject]extended attribute must be annotated with an [Exposed]extended attribute.
Thequalified name of aninterfaceinterface is defined as follows:
Letidentifier be theidentifier ofinterface.
Ifinterface has a [
LegacyNamespace]extended attribute, then:Letnamespace be the identifier argument of the [
LegacyNamespace]extended attribute.Return theconcatenation of «namespace,identifier » withseparatorU+002E FULL STOP (".").
Returnidentifier.
CallbackOrInterfaceOrMixin ::callback CallbackRestOrInterface interface InterfaceOrMixin
InterfaceOrMixin ::InterfaceRest MixinRest
InterfaceRest ::identifier Inheritance { InterfaceMembers } ;
Partial ::partial PartialDefinition
PartialDefinition ::interface PartialInterfaceOrPartialMixin PartialDictionary Namespace
PartialInterfaceOrPartialMixin ::PartialInterfaceRest MixinRest
PartialInterfaceRest ::identifier { PartialInterfaceMembers } ;
InterfaceMembers ::ExtendedAttributeList InterfaceMember InterfaceMembers ε
InterfaceMember ::PartialInterfaceMember Constructor
PartialInterfaceMembers ::ExtendedAttributeList PartialInterfaceMember PartialInterfaceMembers ε
PartialInterfaceMember ::Const Operation Stringifier StaticMember Iterable AsyncIterable ReadOnlyMember ReadWriteAttribute ReadWriteMaplike ReadWriteSetlike
Inheritance ::: identifier ε
The followingIDL fragment demonstrates the definition of two mutually referentialinterfaces. BothHuman andDog inherit fromAnimal. Objects that implement either of those two interfaces will thus have aname attribute.
[Exposed =Window ]interface Animal {attribute DOMString name ;};[Exposed =Window ]interface Human :Animal {attribute Dog ?pet ;};[Exposed =Window ]interface Dog :Animal {attribute Human ?owner ;};
The followingIDL fragment defines simplified versions of a DOMinterfaces and acallback interface.
[Exposed =Window ]interface Node {readonly attribute DOMString nodeName ;readonly attribute Node ?parentNode ;Node appendChild (Node newChild );void addEventListener (DOMString type ,EventListener listener );};callback interface EventListener {void handleEvent (Event event );};
Plain objects can implement acallback interface likeEventListener:
var node= getNode(); // Obtain an instance of Node. var listener= { handleEvent: function ( event) { // ... } }; node. addEventListener( "click" , listener); // This works. node. addEventListener( "click" , function () { ... }); // As does this.
It is not possible for such an object to implement aninterface likeNode, however:
var node= getNode(); // Obtain an instance of Node. var newNode= { nodeName: "span" , parentNode: null , appendChild: function ( newchild) { // ... }, addEventListener: function ( type, listener) { // ... } }; node. appendChild( newNode); // This will throw a TypeError exception.
2.3.Interface mixins
Aninterface mixin is a definition (matching
interface mixin identifier { /* mixin_members... */};
Note:Interface mixins, much likepartial interfaces,are intended for use as a specification editorial aide,allowing a coherent set of functionalities to be grouped together,and included in multiple interfaces, possibly across documents.They are not meant to be exposed through language bindings.Guidance on when to choosepartial interfaces,interface mixins,orpartial interface mixins can be found in§ 2.3.1 Using mixins and partials.
Aninterface mixin is a specification of a set ofinterface mixin members (matching
Theseconstants,regular operations,regular attributes, andstringifiers describe the behaviors that can be implemented by an object,as if they were specified on theinterface thatincludes them.
Static attributes,static operations,special operations except forstringifiers, anditerable,asynchronously iterable,maplike, andsetlike declarations cannot appear ininterface mixin declarations.
As with interfaces, the IDL forinterface mixins can be split into multiple parts by usingpartial interface mixin definitions(matching
interface mixin SomeMixin { /* mixin_members... */};partial interface mixin SomeMixin { /* mixin_members... */};
The order that members appear in has significance for property enumerationin theECMAScript binding.
Note that unlikeinterfaces ordictionaries,interface mixins do not create types.
Of the extended attributes defined in this specification,only the [Exposed] and [SecureContext] extended attributesare applicable tointerface mixins.
Anincludes statement is a definition(matching
interface_identifier includes mixin_indentifier ;
The firstidentifier must reference ainterfaceI.The second identifier must reference aninterface mixinM.
Eachmember ofM is considered to beamember of eachinterfaceI,J,K, … thatincludesM,as if a copy of eachmember had been made.So for a given memberm ofM,interfaceI is considered to have amembermI,interfaceJ is considered to have amembermJ,interfaceK is considered to have amembermK, and so on.Thehost interfaces ofmI,mJ,andmK, areI,J, andK respectively.
Note: In ECMAScript, this implies that eachregular operation declared as amember ofinterface mixinM,and exposed as a data property with abuilt-in function object value,is a distinctbuilt-in function object in eachinterface prototype object whose associatedinterfaceincludesM.Similarly, forattributes, each copy of the accessor property hasdistinctbuilt-in function objects for its getters and setters.
The order of appearance ofincludes statements affects the order in whichinterface mixin areincluded by theirhost interface.
Member order isn’t clearly specified,in particular wheninterface mixins are defined in separate documents.It is discussed inissue #432.
Noextended attributes defined in this specification are applicable toincludes statements.
The followingIDL fragment defines aninterface,Entry, and aninterface mixin,Observable. Theincludes statement specifies thatObservable’smembers are always included on objects implementingEntry.
interface Entry {readonly attribute unsigned short entryType ; // ...};interface mixin Observable {void addEventListener (DOMString type ,EventListener listener ,boolean useCapture ); // ...};Entry includes Observable ;
An ECMAScript implementation would thus have anaddEventListener property in the prototype chain of everyEntry:
var e= getEntry(); // Obtain an instance of Entry. typeof e. addEventListener; // Evaluates to "function".
CallbackOrInterfaceOrMixin ::callback CallbackRestOrInterface interface InterfaceOrMixin
Partial ::partial PartialDefinition
MixinRest ::mixin identifier { MixinMembers } ;
MixinMembers ::ExtendedAttributeList MixinMember MixinMembers ε
MixinMember ::Const RegularOperation Stringifier ReadOnly AttributeRest
IncludesStatement ::identifier includes identifier ;
2.3.1.Using mixins and partials
This section is informative.
Interface mixins allow the sharing ofattributes,constants, andoperations acrossmultipleinterfaces.If you’re only planning to extend a single interface,you might consider using apartial interface instead.
For example, instead of:
interface mixin WindowSessionStorage {readonly attribute Storage sessionStorage ;};Window includes WindowSessionStorage ;
do:
partial interface Window {readonly attribute Storage sessionStorage ;};
Additionally, you can rely on extendinginterface mixins exposed by other specificationsto target common use cases, such asexposing a set ofattributes,constants, oroperations across both window and worker contexts.
For example, instead of the common but verbose:
interface mixin GlobalCrypto {readonly attribute Crypto crypto ;};Window includes GlobalCrypto ;WorkerGlobalScope includes GlobalCrypto ;
you can extend theWindowOrWorkerGlobalScopeinterface mixin using apartial interface mixin:
partial interface mixin WindowOrWorkerGlobalScope {readonly attribute Crypto crypto ;};
2.4.Callback interfaces
Acallback interface is adefinition matching
Note: Acallback interface is not aninterface. The name and syntax are left over fromearlier versions of this standard, where these concepts had more in common.
Acallback interface is a specification of a set ofcallback interface members (matching
callback interface identifier { /* interface_members... */};
Note: See also the similarly namedcallback function definition.
Callback interfaces must define exactly oneregular operation.
Specification authors should not definecallback interfaces unless required to describe the requirements of existing APIs. Instead, acallback function should be used.
The definition ofEventListener as acallback interface is an example of an existing API that needs to allow objects with a given property (in this casehandleEvent) to be considered to implement the interface. For new APIs, and those for which there are no compatibility concerns, using acallback function will allow only afunction object (in the ECMAScript language binding).
Callback interfaces which declareconstants must be annotated with an [Exposed]extended attribute.
CallbackRestOrInterface ::CallbackRest interface identifier { CallbackInterfaceMembers } ;
CallbackInterfaceMembers ::ExtendedAttributeList CallbackInterfaceMember CallbackInterfaceMembers ε
CallbackInterfaceMember ::Const RegularOperation
2.5.Members
Interfaces,interface mixins, andnamespaces are specifications of a set ofmembers (respectively matching
When aninterfaceincludes aninterface mixin, eachmember of the interface mixin is also considered a member of the interface. In contrast,inherited interface members are not considered members of the interface.
The algorithm steps for everyregular operation,regular attribute getter, andregular attribute setter’s defined on aninterface orinterface mixin have access to athis value, which is an IDL value of theinterface type that the member isdeclared on or thatincludes theinterface mixin the member is declared on.
Attribute setter’s algorithm steps also have access tothe given value,which is an IDL value of the type theattribute is declared as.
Interfaces,interface mixins,callback interfaces andnamespaces each support adifferent set ofmembers,which are specified in§ 2.2 Interfaces,§ 2.3 Interface mixins,§ 2.4 Callback interfaces, and§ 2.6 Namespaces,and summarized in the following informative table:
2.5.1.Constants
Aconstant is a declaration (matching
Constants have in the past primarily been used to define named integer codes in the style of an enumeration. The Web platform is moving away from this design pattern in favor of the use of strings. Editors who wish to use this feature are strongly advised to discuss this byfiling an issue before proceeding.
const type constant_identifier = 42;
Theidentifier of aconstant must not be the same as the identifierof anotherinterface member orcallback interface member defined on the sameinterface orcallback interface.The identifier also must notbe "length", "name" or "prototype".
Note: These three names are the names of properties that are defined on theinterface object in the ECMAScript language binding.
The type of a constant (matching
The
Note: These values – in addition to strings and the empty sequence – can also be used to specify thedefault value of a dictionary member orof an optional argument. Note that strings, theempty sequence
The value of the boolean literal tokensboolean valuestrue andfalse.
The value of an
LetS be the sequence of characters matched by the
integer token.Letsign be −1 ifS begins withU+002D HYPHEN-MINUS ("-"), and 1 otherwise.
Letbase be the base of the number based on the characters that follow the optional leadingU+002D HYPHEN-MINUS ("-") character:
- U+0030 DIGIT ZERO ("0"),U+0058 LATIN CAPITAL LETTER X ("X")
- U+0030 DIGIT ZERO ("0"),U+0078 LATIN SMALL LETTER X ("x")
The base is 16.
- U+0030 DIGIT ZERO ("0")
The base is 8.
- Otherwise
The base is 10.
Letnumber be the result of interpreting all remaining characters following the optional leadingU+002D HYPHEN-MINUS ("-") character and any characters indicating the base as an integer specified in basebase.
Returnsign ×number.
The type of an
LetS be the sequence of characters matched by the
decimal token.Letresult be the Mathematical Value that would be obtained ifS were parsed as an ECMAScript
NumericLiteral .If the
decimal token is beingused as the value for afloatorunrestricted float, thenthe value of thedecimal tokenis the IEEE 754 single-precision floating point number closest toresult.Otherwise, the
decimal token is beingused as the value for adoubleorunrestricted double, andthe value of thedecimal tokenis the IEEE 754 double-precision floating point number closest toresult.[IEEE-754]
The value of a constant value specified as
- Type
unrestricted float, constant valueInfinity The value is the IEEE 754 single-precision positive infinity value.
- Type
unrestricted double, constant valueInfinity The value is the IEEE 754 double-precision positive infinity value.
- Type
unrestricted float, constant value-Infinity The value is the IEEE 754 single-precision negative infinity value.
- Type
unrestricted double, constant value-Infinity The value is the IEEE 754 double-precision negative infinity value.
- Type
unrestricted float, constant valueNaN The value is the IEEE 754 single-precision NaN value with the bit pattern 0x7fc00000.
- Type
unrestricted double, constant valueNaN The value is the IEEE 754 double-precision NaN value with the bit pattern 0x7ff8000000000000.
The type of afloat ordouble.
The value of the
IfVT is the type of the value assigned to a constant, andDT is the type of the constant, dictionary member or optional argument itself, then these types mustbe compatible, which is the case ifDT andVT are identical,orDT is anullable type whoseinner type isVT.
Constants are not associated withparticular instances of theinterface orcallback interface on which they appear. It is language binding specific whetherconstants are exposed on instances.
The ECMAScript language binding does however allowconstants to be accessed through objects implementing the IDLinterfaces on which theconstants are declared. For example, with the following IDL:
[Exposed =Window ]interface A {const short rambaldi = 47;};
the constant value can be accessed in ECMAScript either asA.rambaldi orinstanceOfA.rambaldi.
The following extended attributes are applicable to constants:[Exposed],[SecureContext].
Const ::const ConstType identifier = ConstValue ;
ConstValue ::BooleanLiteral FloatLiteral integer
BooleanLiteral ::true false
FloatLiteral ::decimal -Infinity Infinity NaN
ConstType ::PrimitiveType identifier
The followingIDL fragment demonstrates howconstants of the above types can be defined.
[Exposed =Window ]interface Util {const boolean DEBUG =false ;const octet LF = 10;const unsigned long BIT_MASK = 0x0000fc00;const double AVOGADRO = 6.022e23;};
2.5.2.Attributes
Anattribute is aninterface member ornamespace member (matching
regular attributes, which are thoseused to declare that objects implementing theinterface will have a data field member with the givenidentifier
interface interface_identifier {attribute type identifier ;};static attributes, which are usedto declare attributes that are not associated with a particular object implementing the interface
interface interface_identifier {static attribute type identifier ;};
If an attribute has no
Theidentifier of anattribute must not be the same as the identifierof anotherinterface member defined on the sameinterface.The identifier of a static attribute must notbe "prototype".
The type of the attribute is given by the type (matching
The type of the attribute, after resolving typedefs, must not be anullable or non-nullable version of any of the following types:
aunion type that has a nullable or non-nullable sequence type, dictionary,or recordas one of itsflattened member types
The attribute isread only if the
interface interface_identifier {readonly attribute type identifier ;};
Attributes whose type is apromise type must beread only. Additionally, they cannot haveany of theextended attributes [LenientSetter], [PutForwards], [Replaceable], or[SameObject].
Aregular attribute that is notread only can be declared toinherit its getter from an ancestor interface. This can be used to make a read only attributein an ancestor interface be writable on a derived interface. An attributeinherits its getter ifits declaration includes
Note: The grammar ensures that
[Exposed =Window ]interface Ancestor {readonly attribute TheType theIdentifier ;};[Exposed =Window ]interface Derived :Ancestor {inherit attribute TheType theIdentifier ;};
When the
interface interface_identifier {stringifier attribute DOMString identifier ;};
The followingextended attributes are applicable to regular and static attributes:[Exposed],[SameObject],[SecureContext].
The followingextended attributes are applicable only to regular attributes:[LenientSetter],[LenientThis],[PutForwards],[Replaceable],[Unforgeable].
ReadOnlyMember ::readonly ReadOnlyMemberRest
ReadOnlyMemberRest ::AttributeRest MaplikeRest SetlikeRest
ReadWriteAttribute ::inherit AttributeRest AttributeRest
AttributeRest ::attribute TypeWithExtendedAttributes AttributeName ;
AttributeName ::AttributeNameKeyword identifier
AttributeNameKeyword ::async required
ReadOnly ::readonly ε
The followingIDL fragment demonstrates howattributes can be declared on aninterface:
[Exposed =Window ]interface Animal { // A simple attribute that can be set to any string value.readonly attribute DOMString name ; // An attribute whose value can be assigned to.attribute unsigned short age ;};[Exposed =Window ]interface Person :Animal { // An attribute whose getter behavior is inherited from Animal, and need not be // specified in the description of Person.inherit attribute DOMString name ;};
2.5.3.Operations
Anoperation is aninterface member,callback interfacemember ornamespace member (matching
regular operations, whichare those used to declare that objects implementing theinterface will have a method withthe givenidentifier
interface interface_identifier {return_type identifier (/* arguments... */);};special operations,which are used to declare special behavior on objectsimplementing the interface, such as object indexing and stringification
interface interface_identifier { /* special_keyword */return_type identifier (/* arguments... */); /* special_keyword */return_type (/* arguments... */);};static operations,which are used to declare operations that are not associated witha particular object implementing the interface
interface interface_identifier {static return_type identifier (/* arguments... */);};
If an operation has an identifier but no
If an operation has no identifier,then it must be declared to be a special operationusing one of the special keywords.
The identifier of aregular operation orstatic operation must not be the same as the identifierof aconstant orattribute defined on the sameinterface,callback interface ornamespace.The identifier of a static operation must not be "prototype".
Note: The identifier can be the sameas that of another operation on the interface, however.This is how operation overloading is specified.
Theidentifier of astatic operation also must not be the same as the identifierof aregular operation defined on the sameinterface.
Thereturn type of the operation is givenby the type (matchingvoid indicates that the operation returns no value.If the return type is anidentifier followed by
An operation’s arguments (matching
Note: For expressiveness, the identifier of an operation argument can also be specifiedas one of the keywords matching the
If the
If the operation argument type, after resolving typedefs,is anullable type,itsinner type must not be adictionary type.
interface interface_identifier {return_type identifier (type identifier ,type identifier /* , ... */);};
The identifier of each argument must not be the sameas the identifier of another argument in the same operation declaration.
Each argument can be preceded by a list ofextended attributes (matching
interface interface_identifier {return_type identifier ([extended_attributes ]type identifier , [extended_attributes ]type identifier /* , ... */);};
The followingIDL fragment demonstrates howregular operations can be declared on aninterface:
[Exposed =Window ]interface Dimensions {attribute unsigned long width ;attribute unsigned long height ;};[Exposed =Window ]interface Button { // An operation that takes no arguments and returns a boolean.boolean isMouseOver (); // Overloaded operations.void setDimensions (Dimensions size );void setDimensions (unsigned long width ,unsigned long height );};
An operation orconstructor operation is considered to bevariadic if the final argument uses the
interface interface_identifier {return_type identifier (type ...identifier );return_type identifier (type identifier ,type ...identifier );};
Extended attributes thattake an argument list ([NamedConstructor], of thosedefined in this specification) andcallback functions are also considered to bevariadic when the
The followingIDL fragment defines an interface that has two variadic operations:
[Exposed =Window ]interface IntegerSet {readonly attribute unsigned long cardinality ;void union (long ...ints );void intersection (long ...ints );};
In the ECMAScript binding, variadic operations are implemented by functions that can accept the subsequent arguments:
var s= getIntegerSet(); // Obtain an instance of IntegerSet. s. union(); // Passing no arguments corresponding to 'ints'. s. union( 1 , 4 , 7 ); // Passing three arguments corresponding to 'ints'.
A binding for a language that does not support variadic functions might specify that an explicit array or list of integers be passed to such an operation.
An argument is considered to be anoptional argument if it is declared with the
interface interface_identifier {return_type identifier (type identifier ,optional type identifier );};
Optional arguments can also have adefault value specified. If the argument’s identifier is followed by aU+003D EQUALS SIGN ("=") and a value (matching
interface interface_identifier {return_type identifier (type identifier ,optional type identifier = "value");};
It is strongly suggested not to use adefault value ofboolean-typed arguments, as this can be confusing for authors who might otherwise expect the default conversion of
If the type of an argument is adictionary type or aunion type that hasadictionary type as oneof itsflattened member types, and that dictionary type and its ancestors have norequired members, and the argument is either the final argument or isfollowed only byoptional arguments, then the argument must be specified asoptional and have a default value provided.
This is to encourage API designs that do not require authors to pass an empty dictionary value when they wish only to use the dictionary’s default values.
Usually the default value provided will be
When a boolean literal token (
LetS be the sequence ofUnicode scalar values matched bythe
string tokenwith its leading and trailingU+0022 QUOTATION MARK ('"') characters removed.Depending on the type of the argument:
DOMString- anenumeration type
The value of the
string tokenis the sequence of 16 bit unsigned integer code units(hereafter referred to just ascode units)corresponding to the UTF-16 encoding ofS.ByteStringThe value of the
string tokenis the sequence of 8 bit unsigned integer code unitscorresponding to the UTF-8 encoding ofS.USVStringThe value of the
string token isS.
If the type of theoptional argument is anenumeration, then itsdefault value if specified mustbe one of theenumeration’s values.
Optional argument default values can also be specified using thetwo token value
Optional argument default values can also be specified using the two token value
The followingIDL fragment defines aninterface with a singleoperation that can be invoked with two different argument list lengths:
[Exposed =Window ]interface ColorCreator {object createColor (double v1 ,double v2 ,double v3 ,optional double alpha );};
It is equivalent to aninterface that has twooverloadedoperations:
[Exposed =Window ]interface ColorCreator {object createColor (double v1 ,double v2 ,double v3 );object createColor (double v1 ,double v2 ,double v3 ,double alpha );};
The followingIDL fragment defines aninterface with an operation that takes a dictionary argument:
dictionary LookupOptions {boolean caseSensitive =false ;};[Exposed =Window ]interface AddressBook {boolean hasAddressForName (USVString name ,optional LookupOptions options = {});};
IfhasAddressForName is called with only one argument, the second argument will be a default-initializedLookupOptions dictionary, which will causecaseSensitive to be set to
The following extended attributes are applicable to operations:[Default],[Exposed],[NewObject],[SecureContext],[Unforgeable].
DefaultValue ::ConstValue string [ ] { } null
Operation ::RegularOperation SpecialOperation
RegularOperation ::ReturnType OperationRest
SpecialOperation ::Special RegularOperation
Special ::getter setter deleter
OperationRest ::OptionalOperationName ( ArgumentList ) ;
OptionalOperationName ::OperationName ε
OperationName ::OperationNameKeyword identifier
OperationNameKeyword ::includes
ArgumentList ::Argument Arguments ε
Arguments ::, Argument Arguments ε
Argument ::ExtendedAttributeList ArgumentRest
ArgumentRest ::optional TypeWithExtendedAttributes ArgumentName Default Type Ellipsis ArgumentName
ArgumentName ::ArgumentNameKeyword identifier
Ellipsis ::... ε
ArgumentNameKeyword ::async attribute callback const constructor deleter dictionary enum getter includes inherit interface iterable maplike mixin namespace partial readonly required setlike setter static stringifier typedef unrestricted
ReturnType ::Type void
2.5.3.1.toJSON
By declaring atoJSONregular operation,aninterface specifies how to convert the objects that implement it toJSON types.
ThetoJSONregular operation is reserved for this usage.It must take zero arguments and return aJSON type.
TheJSON types are:
nullable types whoseinner type is aJSON type,
annotated types whoseinner type is aJSON type,
union types whosemember types areJSON types,
typedefs whosetype being given a new name is aJSON type,
sequence types whose parameterized type is aJSON type,
frozen array types whose parameterized type is aJSON type,
dictionary types where the types of allmembers declared on the dictionary and all itsinherited dictionaries areJSON types,
records where all of theirvalues areJSON types,
interface types that have a
toJSONoperation declared on themselves orone of theirinherited interfaces.
How thetoJSONregular operation is made available on an object in a language binding,and how exactly theJSON types are converted into a JSON string,is language binding specific.
Note: In the ECMAScript language binding,this is done by exposing atoJSON methodwhich returns theJSON type converted into an ECMAScript valuethat can be turned into a JSON stringby theJSON.stringify() function.Additionally, in the ECMAScript language binding,thetoJSON operation can take a [Default]extended attribute,in which case thedefault toJSON operation is exposed instead.
The followingIDL fragment defines an interfaceTransaction that has atoJSON method defined in prose:
[Exposed =Window ]interface Transaction {readonly attribute DOMString from ;readonly attribute DOMString to ;readonly attribute double amount ;readonly attribute DOMString description ;readonly attribute unsigned long number ;TransactionJSON toJSON ();};dictionary TransactionJSON {Account from ;Account to ;double amount ;DOMString description ;};
ThetoJSONregular operation ofTransactioninterface could be defined as follows:
To invoke thetoJSON() operation of theTransaction interface, run the following steps:
Letjson be a new
TransactionJSONdictionary.For each attributeidentifierattr in « "from", "to", "amount", "description" »:
Letvalue be result ofgetting the underlying value of theattribute identified byattr,giventhis.
Setjson[attr] tovalue.
Returnjson.
In the ECMAScript language binding, there would exist atoJSON() method onTransaction objects:
// Get an instance of Transaction. var txn= getTransaction(); // Evaluates to an object like this: // { // from: "Bob", // to: "Alice", // amount: 50, // description: "books" // } txn. toJSON(); // Evaluates to a string like this: // '{"from":"Bob","to":"Alice","amount":50,"description":"books"}' JSON. stringify( txn);
2.5.4.Constructor operations
If aninterface has aconstructor operation member (matching
Multipleconstructor operations may appear on a giveninterface.For eachconstructor operation on theinterface, there will be a way to attempt toconstruct an instance by passing the specified arguments.
The prose definition of aconstructor operation must either initialize the value passed asthis, or throw an exception.
See§ 3.6.1 Interface object for details on how aconstructor operation is to be implemented.
The following IDL defines two interfaces. The second hasconstructor operations, while the first does not.
[Exposed =Window ]interface NodeList {Node item (unsigned long index );readonly attribute unsigned long length ;};[Exposed =Window ]interface Circle {constructor ();constructor (double radius );attribute double r ;attribute double cx ;attribute double cy ;readonly attribute double circumference ;};
An ECMAScript implementation supporting these interfaces would implement a [[Construct]] internal method on theCircle interface object which would return a new object thatimplements the interface. It would take either zero or one argument.
It is unclear whether theNodeList interface object would implement a [[Construct]] internal method. In any case, trying to use it as a constructor will cause aTypeError to be thrown.<https://github.com/heycam/webidl/issues/698>
var x= new Circle(); // The uses the zero-argument constructor to create a // reference to a platform object that implements the // Circle interface. var y= new Circle( 1.25 ); // This also creates a Circle object, this time using // the one-argument constructor. var z= new NodeList(); // This would throw a TypeError, since no // constructor is declared.
Constructor ::constructor ( ArgumentList ) ;
Ellipsis ::... ε
ArgumentNameKeyword ::async attribute callback const constructor deleter dictionary enum getter includes inherit interface iterable maplike mixin namespace partial readonly required setlike setter static stringifier typedef unrestricted
2.5.5.Special operations
Aspecial operation is adeclaration of a certain kind of special behavior on objects implementingthe interface on which the special operation declarations appear.Special operations are declared by using aspecial keyword in an operation declaration.
There are four kinds of special operations. The table below indicatesfor a given kind of special operation what special keywordis used to declare it and what the purpose of the special operation is:
| Special operation | Keyword | Purpose |
|---|---|---|
| Getters | Defines behavior for when an object is indexed for property retrieval. | |
| Setters | Defines behavior for when an object is indexed for property assignment or creation. | |
| Deleters | Defines behavior for when an object is indexed for property deletion. | |
| Stringifiers | Defines how an object is converted into aDOMString. |
Not all language bindings support all of the four kinds of specialobject behavior. When special operations are declared usingoperations with no identifier, then in language bindings that donot support the particular kind of special operations there simplywill not be such functionality.
The following IDL fragment defines an interface with a getter and a setter:
[Exposed =Window ]interface Dictionary {readonly attribute unsigned long propertyCount ;getter double (DOMString propertyName );setter void (DOMString propertyName ,double propertyValue );};
In language bindings that do not support property getters and setters, objects implementingDictionary will not have that special behavior.
Defining a special operation with anidentifier is equivalent to separating the special operation out into its owndeclaration without an identifier. This approach is allowed tosimplify prose descriptions of an interface’s operations.
The following two interfaces are equivalent:
[Exposed =Window ]interface Dictionary {readonly attribute unsigned long propertyCount ;getter double getProperty (DOMString propertyName );setter void setProperty (DOMString propertyName ,double propertyValue );};
[Exposed =Window ]interface Dictionary {readonly attribute unsigned long propertyCount ;double getProperty (DOMString propertyName );void setProperty (DOMString propertyName ,double propertyValue );getter double (DOMString propertyName );setter void (DOMString propertyName ,double propertyValue );};
A givenspecial keyword must notappear twice on an operation.
Getters and setters come in two varieties: ones thattake aDOMString as a property name,known asnamed property getters andnamed property setters,and ones that take anunsigned long as a property index, known asindexed property getters andindexed property setters.There is only one variety of deleter:named property deleters.See§ 2.5.5.2 Indexed properties and§ 2.5.5.3 Named properties for details.
On a giveninterface,there must exist at most onestringifier, at most onenamed property deleter,and at most one of each variety of getter and setter.
If an interface has a setter of a given variety,then it must also have a getter of thatvariety. If it has anamed property deleter,then it must also have anamed property getter.
Special operations declared using operations must notbevariadic nor have anyoptional arguments.
If an object implements more than oneinterface that defines a given special operation, then it is undefined which (if any)special operation is invoked for that operation.
2.5.5.1.Stringifiers
When aninterface has astringifier, it indicates that objects that implementthe interface have a non-default conversion to a string. As mentioned above,stringifiers can be specified using anoperation declared with the
interface interface_identifier {stringifier DOMString identifier ();stringifier DOMString ();};
If an operation used to declare a stringifier does not have anidentifier, then proseaccompanying the interface must definethestringification behavior of the interface. If the operation does have an identifier,then the object is converted to a string by invoking theoperation to obtain the string.
Stringifiers declared with operations mustbe declared to take zero arguments and return aDOMString.
As a shorthand, if the
interface interface_identifier {stringifier ;};
The following two interfaces are equivalent:
[Exposed =Window ]interface A {stringifier DOMString ();};
[Exposed =Window ]interface A {stringifier ;};
TheDOMString orUSVString.It also must not be placed onastatic attribute.
interface interface_identifier {stringifier attribute DOMString identifier ;};
Stringifier ::stringifier StringifierRest
StringifierRest ::ReadOnly AttributeRest RegularOperation ;
The followingIDL fragment defines an interface that will stringify to the value of itsname attribute:
[Exposed =Window ]interface Student {constructor ();attribute unsigned long id ;stringifier attribute DOMString name ;};
In the ECMAScript binding, using aStudent object in a context where a string is expected will result in the value of the object’sname property being used:
var s= new Student(); s. id= 12345678 ; s. name= '周杰倫' ; var greeting= 'Hello, ' + s+ '!' ; // Now greeting == 'Hello, 周杰倫!'.
The followingIDL fragment defines an interface that has custom stringification behavior that is not specified in the IDL itself.
[Exposed =Window ]interface Student {constructor ();attribute unsigned long id ;attribute DOMString ?familyName ;attribute DOMString givenName ;stringifier DOMString ();};
Thus, prose is required to explain the stringification behavior, such as the following paragraph:
Objects that implement the
Studentinterface must stringify as follows. If the value of thefamilyNameattribute isnull , the stringification of the object is the value of thegivenNameattribute. Otherwise, if the value of thefamilyNameattribute is notnull , the stringification of the object is the concatenation of the value of thegivenNameattribute, a single space character, and the value of thefamilyNameattribute.
An ECMAScript implementation of the IDL would behave as follows:
var s= new Student(); s. id= 12345679 ; s. familyName= 'Smithee' ; s. givenName= 'Alan' ; var greeting= 'Hi ' + s; // Now greeting == 'Hi Alan Smithee'.
2.5.5.2.Indexed properties
Aninterface that defines anindexed property getter is said tosupport indexed properties.By extension, aplatform object is said tosupport indexed properties ifit implements aninterface that itself does.
If an interfacesupports indexed properties,then the interface definition must be accompanied bya description of what indices the object can be indexed with atany given time. These indices are called thesupported property indices.
Interfaces thatsupport indexed properties must defineaninteger-typedattribute named "length".
Indexed property getters mustbe declared to take a singleunsigned long argument.Indexed property setters mustbe declared to take two arguments, where the first is anunsigned long.
interface interface_identifier {getter type identifier (unsigned long identifier );setter type identifier (unsigned long identifier ,type identifier );getter type (unsigned long identifier );setter type (unsigned long identifier ,type identifier );};
The following requirements apply to the definitions of indexed property getters and setters:
If anindexed property getter was specified using anoperation with anidentifier,then the value returned when indexing the object with a givensupported property index is the value that would be returned by invoking the operation, passingthe index as its only argument. If the operation used to declare the indexed property getterdid not have an identifier, then the interface definition must be accompaniedby a description of how todetermine the value of an indexed property for a given index.
If anindexed property setter was specified using an operationwith an identifier,then the behavior that occurs when indexing the object for property assignment with a given supported property index and valueis the same as if the operation is invoked, passingthe index as the first argument and the value as the second argument. If the operation used to declare the indexed property setterdid not have an identifier, then the interface definition must be accompaniedby a description of how toset the value of an existing indexed property and how toset the value of a new indexed property for a given property index and value.
Note that if anindexed property getter orsetter is specified using anoperation with anidentifier, then indexing an object with an integer that is not asupported property index does not necessarily elicit the same behavior as invoking the operation with that index. The actual behavior in this case is language binding specific.
In the ECMAScript language binding, a regular property lookup is done. For example, take the following IDL:
[Exposed =Window ]interface A {getter DOMString toWord (unsigned long index );};
Assume that an object implementingA hassupported property indices in the range 0 ≤index < 2. Also assume that toWord is defined to return its argument converted into an English word. The behavior when invoking theoperation with an out of range index is different from indexing the object directly:
var a= getA(); a. toWord( 0 ); // Evalautes to "zero". a[ 0 ]; // Also evaluates to "zero". a. toWord( 5 ); // Evaluates to "five". a[ 5 ]; // Evaluates to undefined, since there is no property "5".
The followingIDL fragment defines an interfaceOrderedMap which allows retrieving and setting values by name or by index number:
[Exposed =Window ]interface OrderedMap {readonly attribute unsigned long size ;getter any getByIndex (unsigned long index );setter void setByIndex (unsigned long index ,any value );getter any get (DOMString name );setter void set (DOMString name ,any value );};
Since all of the special operations are declared using operations with identifiers, the only additional prose that is necessary is that which describes what keys those sets have. Assuming that theget() operation is defined to returnOrderedMap, then the following two sentences would suffice:
An objectmap implementing
OrderedMapsupports indexed properties with indices in the range 0 ≤index <map.size.Such objects also support a named property for every name that, if passed to
get(), would return a non-null value.
As described in§ 3.8 Legacy platform objects, an ECMAScript implementation would create properties on alegacy platform object implementingOrderedMap that correspond to entries in both the named and indexed property sets. These properties can then be used to interact with the object in the same way as invoking the object’s methods, as demonstrated below:
// Assume map is a legacy platform object implementing the OrderedMap interface. var map= getOrderedMap(); var x, y; x= map[ 0 ]; // If map.length > 0, then this is equivalent to: // // x = map.getByIndex(0) // // since a property named "0" will have been placed on map. // Otherwise, x will be set to undefined, since there will be // no property named "0" on map. map[ 1 ] = false ; // This will do the equivalent of: // // map.setByIndex(1, false) y= map. apple; // If there exists a named property named "apple", then this // will be equivalent to: // // y = map.get('apple') // // since a property named "apple" will have been placed on // map. Otherwise, y will be set to undefined, since there // will be no property named "apple" on map. map. berry= 123 ; // This will do the equivalent of: // // map.set('berry', 123) delete map. cake; // If a named property named "cake" exists, then the "cake" // property will be deleted, and then the equivalent to the // following will be performed: // // map.remove("cake")
2.5.5.3.Named properties
Aninterface that defines anamed property getter is said tosupport named properties.By extension, aplatform object is said tosupport named properties ifit implements aninterface that itself does.
If an interfacesupports named properties,then the interface definition must be accompanied bya description of the ordered set of names that can be used to index the objectat any given time. These names are called thesupported property names.
Named property getters and deleters mustbe declared to take a singleDOMString argument.Named property setters mustbe declared to take two arguments, where the first is aDOMString.
interface interface_identifier {getter type identifier (DOMString identifier );setter type identifier (DOMString identifier ,type identifier );deleter type identifier (DOMString identifier );getter type (DOMString identifier );setter type (DOMString identifier ,type identifier );deleter type (DOMString identifier );};
The following requirements apply to the definitions of named property getters, setters and deleters:
If anamed property getter was specified using anoperation with anidentifier,then the value returned when indexing the object with a givensupported property name is the value that would be returned by invoking the operation, passingthe name as its only argument. If the operation used to declare the named property getterdid not have an identifier, then the interface definition must be accompaniedby a description of how todetermine the value of a named property for a given property name.
If anamed property setter was specified using an operationwith an identifier,then the behavior that occurs when indexing the object for property assignment with a given supported property name and valueis the same as if the operation is invoked, passingthe name as the first argument and the value as the second argument. If the operation used to declare the named property setterdid not have an identifier, then the interface definition must be accompaniedby a description of how toset the value of an existing named property and how toset the value of a new named property for a given property name and value.
If anamed property deleter was specified using an operationwith an identifier,then the behavior that occurs when indexing the object for property deletion with a given supported property nameis the same as if the operation is invoked, passingthe name as the only argument. If the operation used to declare the named property deleterdid not have an identifier, then the interface definition must be accompaniedby a description of how todelete an existing named property for a given property name.
Note: As withindexed properties,if annamed property getter,setter ordeleter is specified using anoperation with anidentifier,then indexing an object with a name that is not asupported property name does not necessarily elicit the same behavior as invoking the operation with that name; the behavioris language binding specific.
2.5.6.Static attributes and operations
Static attributes andstatic operations are ones thatare not associated with a particular instance of theinterface on which it is declared, and is instead associated with the interfaceitself. Static attributes and operations are declared by using the
It is language binding specific whether it is possible to invokea static operation or get or set a static attribute through a referenceto an instance of the interface.
StaticMember ::static StaticMemberRest
StaticMemberRest ::ReadOnly AttributeRest RegularOperation
The followingIDL fragment defines an interfaceCircle that has a static operation declared on it:
[Exposed =Window ]interface Point { /* ... */ };[Exposed =Window ]interface Circle {attribute double cx ;attribute double cy ;attribute double radius ;static readonly attribute long triangulationCount ;static Point triangulate (Circle c1 ,Circle c2 ,Circle c3 );};
In the ECMAScript language binding, thefunction object fortriangulate and the accessor property fortriangulationCount will exist on theinterface object forCircle:
var circles= getCircles(); // an Array of Circle objects typeof Circle. triangulate; // Evaluates to "function" typeof Circle. triangulationCount; // Evaluates to "number" Circle. prototype. triangulate; // Evaluates to undefined Circle. prototype. triangulationCount; // Also evaluates to undefined circles[ 0 ]. triangulate; // As does this circles[ 0 ]. triangulationCount; // And this // Call the static operation var triangulationPoint= Circle. triangulate( circles[ 0 ], circles[ 1 ], circles[ 2 ]); // Find out how many triangulations we have done window. alert( Circle. triangulationCount);
2.5.7.Overloading
If aregular operation orstatic operation defined on aninterface has anidentifier that is the same as the identifier of another operation on thatinterface of the same kind (regular or static), then the operation is said to beoverloaded. When the identifierof an overloaded operation is used to invoke one of theoperations on an object that implements the interface, thenumber and types of the arguments passed to the operationdetermine which of the overloaded operations is actuallyinvoked.Constructor operations can be overloaded too.There are some restrictions on the argumentsthat overloaded operations and constructors can bespecified to take, and in order to describe these restrictions,the notion of aneffective overload set is used.
Operations must not be overloaded acrossinterface,partial interface,interface mixin, andpartial interface mixin definitions.
For example, the overloads for bothf andg are disallowed:
[Exposed =Window ]interface A {void f ();};partial interface A {void f (double x );void g ();};partial interface A {void g (DOMString x );};
Note thatconstructor operations and [NamedConstructor]extended attributes are disallowed from appearing onpartial interface definitions, so there is no need to also disallow overloading for constructors.
Aneffective overload set represents the allowable invocations for a particularoperation,constructor (specified with aconstructor operation or [NamedConstructor]), orcallback function.The algorithm tocompute the effective overload set operates on one of the following four types of IDL constructs, and listed with them below arethe inputs to the algorithm needed to compute the set.
- For regular operations
- For static operations
theinterface on which theoperations are to be found
theidentifier of the operations
the number of arguments to be passed
- For constructors
theinterface on which theconstructor operations are to be found
the number of arguments to be passed
- For named constructors
theinterface on which the [
NamedConstructor]extended attributes are to be foundtheidentifier of the named constructors
the number of arguments to be passed
Aneffective overload set is used, among other things, to determine whether there areambiguities in the overloaded operations and constructors specified on an interface.
Theitems of aneffective overload set aretuples of the form(callable,type list,optionality list)whoseitems are described below:
Acallable is anoperation if theeffective overload set is forregular operations,static operations, orconstructor operations; and it is anextended attribute if theeffective overload set is fornamed constructors.
Atype list is alist of IDL types.
Anoptionality list is alist ofthree possibleoptionality values – "required", "optional" or "variadic" –indicating whether the argument at a given index wasdeclared as beingoptional or corresponds to avariadic argument.
Eachtuple represents an allowable invocation of the operation,constructor, or callback function with an argument value list of the given types.Due to the use ofoptional arguments andvariadic operationsand constructors, there may be multiple items in aneffective overload set identifyingthe same operation or constructor.
the identifier of the operation or named constructor isA
the argument count isN
the interface isI
Whenever an argument of an extended attribute is mentioned, it is referring to an argument of the extended attribute’snamed argument list.
LetS be anordered set.
LetF be anordered set withitems as follows,according to the kind ofeffective overload set:
- For regular operations
The elements ofF are theregular operations withidentifierA defined on interfaceI.
- For static operations
The elements ofF are thestatic operations withidentifierA defined on interfaceI.
- For constructors
The elements ofF are theconstructor operations on interfaceI.
- For named constructors
The elements ofF are the[
NamedConstructor]extended attributes on interfaceI whosenamed argument lists’ identifiers areA.
Letmaxarg be the maximum number of arguments the operations,constructor extended attributes or callback functions inF are declared to take.Forvariadic operations and constructor extended attributes,the argument on which the ellipsis appears counts as a single argument.
Note: So
void f(long x, long... y);is considered to be declared to take two arguments.Letmax bemax(maxarg,N).
For each operation or extended attributeX inF:
Letarguments be thelist of argumentsX is declared to take.
Letn be thesize ofarguments.
Lettypes be atype list.
LetoptionalityValues be anoptionality list.
For eachargument inarguments:
IfX is declared to bevariadic, then:
Leti ben − 1.
Whilei ≥ 0:
Ifarguments[i] is notoptional (i.e., it is not marked as "optional" and is nota final, variadic argument), thenbreak.
Lett be atype list.
Leto be anoptionality list.
Note: ifi is 0, this means to add toS the tuple (X, « », « »);(where "« »" represents anempty list).
Seti toi − 1.
ReturnS.
For the following interface:
[Exposed =Window ]interface A { /* f1 */void f (DOMString a ); /* f2 */void f (Node a ,DOMString b ,double ...c ); /* f3 */void f (); /* f4 */void f (Event a ,DOMString b ,optional DOMString c ,double ...d );};
assumingNode andEvent are two other interfaces of which no object can implement both, theeffective overload set forregular operations with identifierf and argument count 4 is:
« (f1, « DOMString », « required »), (f2, « Node, DOMString », « required, required »), (f2, « Node, DOMString, double », « required, required, variadic »), (f2, « Node, DOMString, double, double », « required, required, variadic, variadic »), (f3, « », « »), (f4, « Event, DOMString », « required, required »), (f4, « Event, DOMString, DOMString », « required, required, optional »), (f4, « Event, DOMString, DOMString, double », « required, required, optional, variadic »)»
Two types aredistinguishable ifthe following algorithm returnstrue.
If one typeincludes a nullable type and the other type eitherincludes a nullable type,is aunion type withflattened member types including adictionary type, oris adictionary type,returnfalse.
If both types are either aunion type ornullableunion type,returntrue if each member type of the oneis distinguishable with each member type of the other,orfalse otherwise.
If one type is aunion type or nullable union type,returntrue if eachmember type of the union type is distinguishablewith the non-union type,orfalse otherwise.
Consider the two "innermost" types derived by taking each type’sinner type if it is anannotated type, and then taking itsinner type inner typeif the result is anullable type. If these two innermost types appear or are in categoriesappearing in the following table and there is a “●” mark in the corresponding entryor there is a letter in the corresponding entry and the designated additionalrequirement below the table is satisfied, then returntrue.Otherwise returnfalse.
Categories:
- interface-like
- dictionary-like
- sequence-like
booleannumeric typesstring typesobjectsymbolinterface-likecallback functiondictionary-likesequence-likeboolean ● ● ● ● ● ● ● ● numeric types ● ● ● ● ● ● ● string types ● ● ● ● ● ● object ● symbol ● ● ● ● interface-like (a) ● ● ● callback function ● dictionary-like ● sequence-like The two identified interface-like types arenot the same, and no singleplatform object implements bothinterface-like types.
doubleandDOMStringare distinguishable because there is a ● at the intersection ofnumeric types withstring types.doubleandlongare not distinguishable because they are bothnumeric types, and there is no ● or letter at the intersection ofnumeric types withnumeric types.Given:callback interface CBIface {void handle ();};[Exposed =Window ]interface Iface {attribute DOMString attr2 ;};dictionary Dict {DOMString field1 ;};CBIfaceis distinguishable fromIfacebecause there’s a ● at the intersection of dictionary-like and interface-like, but it is not distinguishable fromDictbecause there’s no ● at the intersection of dictionary-like and itself.Promise types do not appear in the above table, and as a consequence are not distinguishable with any other type.
If there is more than oneitem in aneffective overload set that has a giventype listsize,then for those items there must be an indexi such thatfor each pair of items the types at indexi aredistinguishable.The lowest such index is termed thedistinguishing argument index for the items of theeffective overload set with the given type list size.
Consider theeffective overload set shown in the previous example. There are multiple items in the set with type lists 2, 3 and 4. For each of these type list size, thedistinguishing argument index is 0, sinceNode andEvent aredistinguishable.
The following use of overloading however is invalid:
[Exposed =Window ]interface B {void f (DOMString x );void f (USVString x );};
In addition, for each indexj, wherej is less than thedistinguishing argument index for a given type list size, the types at indexj inall of the items’ type lists must be the same,and theoptionality values at indexj in all of the items’ optionality lists mustbe the same.
The following is invalid:
[Exposed =Window ]interface B { /* f1 */void f (DOMString w ); /* f2 */void f (long w ,double x ,Node y ,Node z ); /* f3 */void f (double w ,double x ,DOMString y ,Node z );};
For argument count 4, theeffective overload set is:
« (f1, « DOMString », « required »), (f2, « long, double, Node, Node », « required, required, required, required »), (f3, « double, double, DOMString, Node », « required, required, required, required »)»
Looking at items with type list size 4, thedistinguishing argument index is 2, sinceNode andDOMString aredistinguishable. However, since the arguments in these two overloads at index 0 are different, the overloading is invalid.
2.5.7.1.Overloading vs. union types
This section is informative.
For specifications defining IDLoperations, it might seem thatoverloads and acombination ofunion types andoptional arguments have some feature overlap.
It is first important to note thatoverloads have different behaviors thanuniontypes oroptional arguments, and onecannot be fully defined using the other (unless,of course, additional prose is provided, which can defeat the purpose of the Web IDL type system).For example, consider thestroke() operations defined on theCanvasDrawPath interface[HTML]:
interface CanvasDrawPathExcerpt {void stroke ();void stroke (Path2D path );};
Per the ECMAScript language binding, callingstroke(undefined) on an objectimplementingCanvasDrawPathExcerpt would attempt to call the secondoverload, yielding aTypeError sincePath2D. However, if the operations were insteaddefined withoptional arguments and merged into one,
interface CanvasDrawPathExcerptOptional {void stroke (optional Path2D path );};
theoverload resolution algorithm would treat thepath argument asnotpresent given the same callstroke(undefined), and not throw any exceptions.
Note: For this particular example, the latter behavior is actually what Web developers wouldgenerally expect. IfCanvasDrawPath were to be designed today,optional arguments would beused forstroke().
Additionally, there are semantic differences as well.Union types are usually used in the sensethat "any of the types would work in about the same way". In contrast,overloaded operations aredesigned to map well to language features such as C++ overloading, and are usually a better fit foroperations with more substantial differences in what they do given arguments of different types.However, in most cases, operations with such substantial differences are best off with differentnames to avoid confusion for Web developers, since the ECMAScript language does not providelanguage-level overloading. As such, overloads are rarely appropriate for new APIs, instead oftenappearing in legacy APIs or in specialized circumstances.
That being said, we offer the following recommendations and examples in case of difficulties todetermine what Web IDL language feature to use:
In the unusual case where the operation needs to return values of different types for differentargument types,overloading will result in more expressive IDL fragments.This is almost never appropriate API design, and separate operations with distinctnames usually are a better choice for such cases.
Suppose there is an operation
calculate()that accepts along,DOMString, orCalculatableInterface(aninterface type) as itsonly argument, and returns a value of the same type as its argument. It would be clearer towrite the IDL fragment usingoverloaded operations asinterface A {long calculate (long input );DOMString calculate (DOMString input );CalculatableInterface calculate (CalculatableInterface input );};than using aunion type with atypedef as
typedef (long or DOMString or CalculatableInterface )Calculatable ;interface A {Calculatable calculate (Calculatable input );};which does not convey the fact that the return value is always of the same type asinput.
The problem is exacerbated when one of the overloads has a return type of
void, sinceunion types cannot even containvoidas amember type. In that case, a return typeofanyneeds to be used with appropriate prose defining the return type, further decreasingexpressiveness.If the specified
calculate()is a new API and does not have anycompatibility concerns, it is suggested to use different names for the overloaded operations,perhaps asinterface A {long calculateNumber (long input );DOMString calculateString (DOMString input );CalculatableInterface calculateCalculatableInterface (CalculatableInterface input );};which allows Web developers to write explicit and unambiguous code.
When the operation has significantly different semantics for different argument types orlengths,overloading is preferred. Again, in such scenarios, it is usually betterto create separate operations with distinct names, but legacy APIs sometimes follow thispattern.
As an example, the
supports(property, value)andsupports(conditionText)operations of theCSSinterface are defined as thefollowing IDL fragment[CSS3-CONDITIONAL][CSSOM].partial interface CSS {static boolean supports (CSSOMString property ,CSSOMString value );static boolean supports (CSSOMString conditionText );};Usingoptional arguments one can rewrite the IDL fragment as follows:
partial interface CSSExcerptOptional {static boolean supports (CSSOMString propertyOrConditionText ,optional CSSOMString value );};Even though the IDL is shorter in the second version, two distinctively different concepts areconflated in the first argument. Withoutoverloads, the question "isproperty orconditionText paired withvalue?"is much more difficult to answer without reading the prose definition of the operation. Thismakes the second version remarkably less readable than the first.
Another consideration is that the prose foroverloaded operations can be specified inseparate blocks, which can aid in both reading and writing specifications. This is not the caseforoptional arguments. This means that in the first case the specification author can writethe prose definition of the operations as:
The
supports(property,value)method, when called, must run these steps:…
The
supports(conditionText)method, when called, must run these steps:…
Yet usingvalue as anoptional argument, the specification author has touse more boilerplate-style text to effectively replicate theoverload resolution algorithm.
The
supports(propertyOrConditionText,value)method, when called, must run these steps:Ifvalue is given, then:
Letproperty bepropertyOrConditionText.
…
Otherwise:
LetconditionText bepropertyOrConditionText.
…
If the two overloads have little to no shared parts, it is better to leave overload resolutionto the IDL mechanism.
If the operation accepts multiple types for multiple arguments with no coupling between types ofdifferent arguments,union types can sometimes be the only viable solution.
typedef (long long or DOMString or CalculatableInterface )SupportedArgument ;interface A {void add (SupportedArgument operand1 ,SupportedArgument operand2 );};For the
add()operation above, to specify it usingoverloads would requireinterface A {void add (long long operand1 ,long long operand2 );void add (long long operand1 ,DOMString operand2 );void add (long long operand1 ,CalculatableInterface operand2 );void add (DOMString operand1 ,long long operand2 );void add (DOMString operand1 ,DOMString operand2 );void add (DOMString operand1 ,CalculatableInterface operand2 );void add (CalculatableInterface operand1 ,long long operand2 );void add (CalculatableInterface operand1 ,DOMString operand2 );void add (CalculatableInterface operand1 ,CalculatableInterface operand2 );};and nine times the corresponding prose!
Specification authors are encouraged to treat missing argument and
undefined argument the same way in the ECMAScript language binding.Given the following IDL fragment:
interface A {void foo ();void foo (Node ?arg );};Using the ECMAScript language binding, calling
foo(undefined)andfoo(null)would both run the steps corresponding to thefoo(arg)operation, witharg set to null, whilefoo()alonewould go to the first overload. This can be a surprising behavior for many API users. Instead,specification authors are encouraged to use anoptional argument, which would categorizebothfoo()andfoo(undefined)as "arg isnotpresent".interface A {void foo (optional Node ?arg );};In general, optionality is best expressed using the
optional keyword, and notusing overloads.
When the case fits none of the categories above, it is up to the specification author to choose thestyle, since it is most likely that either style would sufficiently and conveniently describe theintended behavior. However, the definition andconversion algorithms ofunion types andoptional arguments are simpler to implement and reason about thanthose ofoverloads, and usually result in more idiomatic APIsin the ECMAScript language binding. Thus, unless any other considerations apply,union types (and/oroptional arguments) are the default choice.
Specifications are also free to mix and match union types and overloads, if the author finds itappropriate and convenient.
2.5.8.Iterable declarations
Aninterface can be declared to beiterable by using aniterable declaration (matching
interface interface_identifier {iterable <value_type >;iterable <key_type ,value_type >;};
Objects implementing an interface that is declared to be iterablesupport being iterated over to obtain a sequence of values.
Note: In the ECMAScript language binding, an interface that is iterablewill haveentries,forEach,keys,values, and@@iterator properties on itsinterface prototype object.
If a single type parameter is given, then the interface has avalue iterator and providesvalues of the specified type.If two type parameters are given, then the interface has apair iterator and providesvalue pairs with the given types.
Avalue pair, given a key type and a value type, is astruct with twoitems:
anitem whosename is "key", which is referred to as thevalue pair'skey, and whose value is an IDL value of the key type;
anitem whosename is "value", which is referred to as thevalue pair'svalue, and whose value is an IDL value of thevalue type.
Avalue iterator must only be declared on an interfacethatsupports indexed properties.The value-type of thevalue iterator must be the same as the type returned bytheindexed property getter.Avalue iterator is implicitlydefined to iterate over the object’s indexed properties.
Apair iterator must not be declared on an interfacethatsupports indexed properties.
Prose accompanying aninterface with apair iterator must define alist ofvalue pairs for each instance of theinterface, which is the list ofvalue pairs to iterate over.
The ECMAScript forEach method that is generated for avalue iterator invokes its callback like Array.prototype.forEach does, and the forEach method for apair iterator invokes its callback like Map.prototype.forEach does.
Sincevalue iterators are currently allowed only on interfaces thatsupport indexed properties, it makes sense to use an Array-like forEach method. There may be a need forvalue iterators (a) on interfaces that do notsupport indexed properties, or (b) with a forEach method that instead invokes its callback like Set.protoype.forEach (where the key is the same as the value). If you’re creating an API that needs such a forEach method, pleasefile an issue.
Note: This is howarray iterator objects work.For interfaces thatsupport indexed properties,the iterator objects returned byentries,keys,values, and@@iterator areactualarray iterator objects.
Interfaces with iterable declarations must nothave anyinterface members named "entries", "forEach","keys", or "values",or have anyinherited interfaces that havemembers with these names.
Consider the following interfaceSessionManager, which allows access to a number ofSession objects keyed by username:
[Exposed =Window ]interface SessionManager {Session getSessionForUser (DOMString username );iterable <DOMString ,Session >;};[Exposed =Window ]interface Session {readonly attribute DOMString username ; // ...};
The behavior of the iterator could be defined like so:
Thevalue pairs to iterate over are the list ofvalue pairs with thekey being the username and thevalue being the open
Sessionobject on theSessionManagerobject corresponding to that username, sorted by username.
In the ECMAScript language binding, theinterface prototype object for theSessionManagerinterface has avalues method that is a function, which, when invoked, returns an iterator object that itself has anext method that returns the next value to be iterated over. It haskeys andentries methods that iterate over the usernames of session objects and username/Session object pairs, respectively. It also has a@@iterator method that allows aSessionManager to be used in afor..of loop that has the same value as theentries method:
// Get an instance of SessionManager. // Assume that it has sessions for two users, "anna" and "brian". var sm= getSessionManager(); typeof SessionManager. prototype. values; // Evaluates to "function" var it= sm. values(); // values() returns an iterator object typeof it. next; // Evaluates to "function" // This loop will log "anna" and then "brian". for (;;) { let result= it. next(); if ( result. done) { break ; } let session= result. value; console. log( session. username); } // This loop will also log "anna" and then "brian". for ( let usernameof sm. keys()) { console. log( username); } // Yet another way of accomplishing the same. for ( let [ username, session] of sm) { console. log( username); }
An interface must not have more than oneiterable declaration.Theinherited interfaces of an interface with aniterable declaration must not also have aniterable declaration.An interface with aniterable declaration and itsinherited interfaces must not have amaplike declaration,setlike declaration, orasynchronously iterable declaration.
The following extended attributes are applicable toiterable declarations:[Exposed],[SecureContext].
Iterable ::iterable < TypeWithExtendedAttributes OptionalType > ;
OptionalType ::, TypeWithExtendedAttributes ε
2.5.9.Asynchronously iterable declarations
Aninterface can be declared to be asynchronously iterable by using anasynchronously iterable declaration (matching
interface interface_identifier {async iterable <key_type ,value_type >;};
Objects thatimplement aninterface that is declared to be asynchronously iterable supportbeing iterated over asynchronously to obtain a sequence of values.
Note: In the ECMAScript language binding, an interface that is asynchronously iterable will haveentries,keys,values,and@@asyncIterator properties on itsinterface prototype object.
Prose accompanying aninterface with anasynchronously iterable declaration must define aget the next iteration result algorithm.This algorithm receives the instance of theinterface that is being iterated, as well as theasync iterator itself (which can be useful for storing state).It must return aPromise that either rejects, resolves with undefined to signal the end of theiteration, or resolves with a tuple containing two elements:
a value of the first type given in the declaration;
a value of the second type given in the declaration.
The prose may also define anasynchronous iterator return algorithm. Thisalgorithm receives the instance of theinterface that is being iterated, the async iteratoritself, and a single argument value of typeany. This algorithm is invoked in the case ofpremature termination of the async iterator. It must return aPromise; if that promisefulfills, its fulfillment value will be ignored, but if it rejects, that failure will be passed onto users of the async iterator API.
In the ECMAScript binding, this algorithm allows customizing the behavior when theasync iterator’sreturn() method is invoked. This most commonly occurs when abreak orreturn statement causes an exit from afor-await-of loop.
We could add a similar hook forthrow(). So far there has been no need,but if you are creating an API that needs such capabilities, pleasefile an issue.
The prose may also defineasynchronous iterator initialization steps. Thesereceive the instance of theinterface being iterated, as well as the newly-createditerator object.
Interfaces with anasynchronously iterable declaration must not have anyinterface members named "entries", "keys", or "values",or have anyinherited interfaces that haveinterface members with these names.
Consider the following interfaceSessionManager, which allows access to a number ofSession objects keyed by username:
[Exposed =Window ]interface SessionManager {Session getSessionForUser (DOMString username );async iterable <DOMString ,Session >;};[Exposed =Window ]interface Session {readonly attribute DOMString username ; // ...};
The behavior of the iterator could be defined like so:
Theasynchronous iterator initialization steps for a
SessionManagerasync iteratoriterator are:
Setiterator’scurrent state to "notyet started".
Toget the next iteration result for a
SessionManagermanager and its async iteratoriterator:
Letpromise be a new promise.
Letkey be the following value, if it exists, or null otherwise:
- Ifiterator’scurrent state is "not yet started"
the smallest username inmanager’s open sessions, in lexicographical order
- Otherwise
the smallest username inmanager’s open sessions that is greater thaniterator’s current state, in lexicographical order
Note:iterator’scurrent state might no longer bepresent in the open sessions.
Ifkey is null, then:
Resolvepromise with undefined.
Otherwise:
Letsession be the
Sessionobject corresponding tokey.Resolvepromise with (username,session).
Setiterator’scurrent state tousername.
Returnpromise.
In the ECMAScript language binding, theinterface prototype object for theSessionManagerinterface has avalues method that is a function, which, when invoked, returns an asynchronous iterator object that itself has anext method that returns the next value to be iterated over. It haskeys andentries methods that iterate over the usernames of session objects and (username,Session) object pairs, respectively. It also has a@@asyncIterator method that allows aSessionManager to be used in afor await..of loop that has the same value as theentries method:
// Get an instance of SessionManager. // Assume that it has sessions for two users, "anna" and "brian". var sm= getSessionManager(); typeof SessionManager. prototype. values; // Evaluates to "function" var it= sm. values(); // values() returns an iterator object typeof it. next; // Evaluates to "function" // This loop will log "anna" and then "brian". for await( let usernameof sm. keys()) { console. log( username); } // Yet another way of accomplishing the same. for await( let [ username, session] of sm) { console. log( username); }
Aninterface must not have more than oneasynchronously iterable declaration.Theinherited interfaces of aninterface with anasynchronously iterable declaration must not also have anasynchronously iterable declaration.Aninterface with anasynchronously iterable declaration and itsinherited interfaces must not have amaplike declaration,setlike declaration, oriterable declaration.
The following extended attributes are applicable toasynchronously iterable declarations:[Exposed],[SecureContext].
theseextended attributes are not currently taken into account.When they are, the effect will be as you would expect.
AsyncIterable ::async iterable < TypeWithExtendedAttributes , TypeWithExtendedAttributes > ;
2.5.10.Maplike declarations
Aninterface can be declared to bemaplike by using amaplike declaration (matching
interface interface_identifier {readonly maplike <key_type ,value_type >;maplike <key_type ,value_type >;};
Objects implementing an interface that is declared to be maplikerepresent an ordered list of key–value pairs known as itsmap entries.The types used for the keys and values are given in the anglebrackets of the maplike declaration. Keys are required to be unique.
Themap entries of an objectimplementing amaplike interface is empty atthe of the object’s creation. Prose accompanying the interface candescribe how themap entries of an object change.
Maplike interfaces support an API for querying the map entriesappropriate for the language binding. If the
Note: In the ECMAScript language binding, the API for interactingwith the map entries is similar to that available on ECMAScriptMap objects. If theentries,forEach,get,has,keys,values,@@iterator methods, and asize getter.For read–write maplikes, it also includesclear,delete, andset methods.
Maplike interfaces must nothave anyinterface members named "entries", "forEach","get", "has","keys", "size", or"values",or have anyinherited interfaces that havemembers with these names.Read–write maplike interfaces must nothave anyattributes orconstants named"clear", "delete",or "set", or have anyinherited interfaces that haveattributes orconstants with these names.
Note: Operations named "clear", "delete",or "set" are allowed on read–write maplikeinterfaces and will prevent the default implementation of these methods beingadded to the interface prototype object in the ECMAScript language binding.This allows the default behavior of these operations to be overridden.
An interface must not have more than onemaplike declaration.Theinherited interfaces of a maplike interface must notalso have amaplike declaration.A maplike interface and itsinherited interfaces must not have aniterable declaration,anasynchronously iterable declaration,asetlike declaration, oranindexed property getter.
ReadOnlyMember ::readonly ReadOnlyMemberRest
ReadWriteMaplike ::MaplikeRest
MaplikeRest ::maplike < TypeWithExtendedAttributes , TypeWithExtendedAttributes > ;
Noextended attributes defined in this specification are applicable tomaplike declarations.
2.5.11.Setlike declarations
Aninterface can be declared to besetlike by using asetlike declaration (matching
interface interface_identifier {readonly setlike <type >;setlike <type >;};
Objects implementing an interface that is declared to be setlikerepresent an ordered list of values known as itsset entries.The type of the values is given in the anglebrackets of the setlike declaration. Values are required to be unique.
Theset entries of an objectimplementing asetlike interface is empty atthe of the object’s creation. Prose accompanying the interface candescribe how theset entries of an object change.
Setlike interfaces support an API for querying the set entriesappropriate for the language binding. If the
Note: In the ECMAScript language binding, the API for interactingwith the set entries is similar to that available on ECMAScriptSet objects. If theentries,forEach,has,keys,values,@@iterator methods, and asize getter.For read–write setlikes, it also includesadd,clear, anddelete methods.
Setlike interfaces must nothave anyinterface members named "entries", "forEach","has", "keys","size", or "values",or have anyinherited interfaces that havemembers with these names.Read–write setlike interfaces must nothave anyattributes orconstants named"add", "clear",or "delete", or have anyinherited interfaces that haveattributes orconstants with these names.
Note: Operations named "add", "clear",or "delete" are allowed on read–write setlikeinterfaces and will prevent the default implementation of these methods beingadded to the interface prototype object in the ECMAScript language binding.This allows the default behavior of these operations to be overridden.
An interface must not have more than onesetlike declaration.Theinherited interfaces of a setlike interface must notalso have asetlike declaration.A setlike interface and itsinherited interfaces must not have aniterable declaration,anasynchronously iterable declaration,amaplike declaration, oranindexed property getter.
ReadOnlyMember ::readonly ReadOnlyMemberRest
ReadWriteSetlike ::SetlikeRest
SetlikeRest ::setlike < TypeWithExtendedAttributes > ;
Noextended attributes defined in this specification are applicable tosetlike declarations.
2.6.Namespaces
Anamespace is a definition (matching
namespace identifier { /* namespace_members... */};
A namespace is a specification of a set ofnamespace members (matching
As with interfaces, the IDL for namespaces can be split into multiple parts by usingpartial namespace definitions(matching
namespace SomeNamespace { /* namespace_members... */};partial namespace SomeNamespace { /* namespace_members... */};
Note: As with partial interface definitions, partial namespace definitions are intended foruse as a specification editorial aide, allowing the definition of a namespace to beseparated over more than one section of the document, and sometimes multipledocuments.
The order that members appear in has significance for property enumeration in theECMAScript binding.
Note that unlike interfaces or dictionaries, namespaces do not create types.
Of the extended attributes defined in this specification, only the [Exposed] and [SecureContext] extended attributes are applicable to namespaces.
Namespaces must be annotated with the [Exposed]extended attribute.
Partial ::partial PartialDefinition
Namespace ::namespace identifier { NamespaceMembers } ;
NamespaceMembers ::ExtendedAttributeList NamespaceMember NamespaceMembers ε
NamespaceMember ::RegularOperation readonly AttributeRest
The followingIDL fragment defines anamespace.
namespace VectorUtils {readonly attribute Vector unit ;double dotProduct (Vector x ,Vector y );Vector crossProduct (Vector x ,Vector y );};
An ECMAScript implementation would then expose a globalVectorUtils data property which was a simple object (with prototype%ObjectPrototype%) with enumerable data properties for each declared operation, and enumerable get-only accessors for each declared attribute:
Object. getPrototypeOf( VectorUtils); // Evaluates to Object.prototype. Object. keys( VectorUtils); // Evaluates to ["dotProduct", "crossProduct"]. Object. getOwnPropertyDescriptor( VectorUtils, "dotProduct" ); // Evaluates to { value: <a function>, enumerable: true, configurable: true, writable: true }. Object. getOwnPropertyDescriptor( VectorUtils, "unit" ); // Evaluates to { get: <a function>, enumerable: true, configurable: true }.
2.7.Dictionaries
Adictionary is a definition (matching
dictionary identifier { /* dictionary_members... */};
Dictionaries are always passed by value. In language bindings where a dictionary is represented by an object of some kind, passing adictionary to aplatform object will not result in a reference to the dictionary being kept by that object.Similarly, any dictionary returned from a platform object will be a copy and modifications made to it will not be visible to the platform object.
A dictionary can be defined toinherit from another dictionary.If the identifier of the dictionary is followed by a colon and aidentifier,then that identifier identifies the inherited dictionary. The identifiermust identify a dictionary.
A dictionary must not be declared such thatits inheritance hierarchy has a cycle. That is, a dictionaryA cannot inherit from itself, nor can it inherit from anotherdictionaryB that inherits fromA, and so on.
dictionary Base { /* dictionary_members... */};dictionary Derived :Base { /* dictionary_members... */};
Theinherited dictionaries ofa given dictionaryD is the set of all dictionaries thatD inherits from, directly or indirectly. IfD does notinherit from another dictionary, then the set is empty. Otherwise, the setincludes the dictionaryE thatDinherits from and all ofE’sinherited dictionaries.
A dictionary value of typeD can have key–value pairs correspondingto the dictionary members defined onD and on any ofD’sinherited dictionaries.On a given dictionary value, the presence of each dictionary memberis optional, unless that member is specified as required.A dictionary member is said to bepresent in a dictionary value if the valuecontains an entry with the key given by the member’sidentifier, otherwise it isnot present.Dictionary members can also optionally have adefault value, which isthe value to use for the dictionary member when passing a value to aplatform object that doesnot have a specified value. Dictionary members with default values arealways considered to be present.
In the ECMAScript binding, a value of
Anordered map with stringkeys can be implicitly treated as a dictionary value of aspecific dictionaryD if all of itsentries correspond todictionary members, in thecorrect order and with the correct types, and with appropriateentries for any requireddictionary members.
dictionary Descriptor {DOMString name ;sequence <unsigned long >serviceIdentifiers ;};
ADescriptor dictionary could be created as in the following steps:
Letidentifiers be « 1, 3, 7 ».
Return «[ "name" → "test", "serviceIdentifiers" →identifiers ]».
As withoperation argument default values, it is strongly suggested not to useboolean-typeddictionary members, as this can be confusing for authors who might otherwise expect the default conversion of
Eachdictionary member (matching
If the type of thedictionary member, after resolving typedefs,is anullable type,itsinner type must not be adictionary type.
dictionary identifier {type identifier ;};
If the identifier is followed by aU+003D EQUALS SIGN ("=") and a value (matching
dictionary identifier {type identifier = "value";};
When a boolean literal token (
If the type of thedictionary member is anenumeration, then itsdefault value if specified mustbe one of theenumeration’s values.
If the type of the dictionary member is preceded by the
dictionary identifier {required type identifier ;};
The type of a dictionary member must not includethe dictionary it appears on. A type includes a dictionaryD if at least one of the following is true:
the type isD
the type is a dictionary thatinherits fromD
the type is anullable type whoseinner type includesD
the type is asequence type orfrozen array whose element type includesD
the type is aunion type,one of whosemember types includesD
the type is a dictionary, one of whose members or inherited members hasa type that includesD
the type is
record<K,V>whereV includesD
As with interfaces, the IDL for dictionaries can be split into multiple partsby usingpartial dictionary definitions(matching
dictionary SomeDictionary { /* dictionary_members... */};partial dictionary SomeDictionary { /* dictionary_members... */};
Note: As with partial interface definitions, partial dictionary definitions are intended for use as a specificationeditorial aide, allowing the definition of an interface to be separatedover more than one section of the document, and sometimes multiple documents.
The order of thedictionary members on a given dictionary is such that inherited dictionary members are orderedbefore non-inherited members, and the dictionary members on the onedictionary definition (including any partial dictionary definitions) areordered lexicographically by the Unicode codepoints that comprise theiridentifiers.
For example, with the following definitions:
dictionary B :A {long b ;long a ;};dictionary A {long c ;long g ;};dictionary C :B {long e ;long f ;};partial dictionary A {long h ;long d ;};
the order of thedictionary members of a dictionary value of typeC is c, d, g, h, a, b, e, f.
Dictionaries are required to have their members ordered because in some language bindings the behavior observed when passing a dictionary value to a platform object depends on the order the dictionary members are fetched. For example, consider the following additional interface:
[Exposed =Window ]interface Something {void f (A a );};
and this ECMAScript code:
var something= getSomething(); // Get an instance of Something. var x= 0 ; var dict= { }; Object. defineProperty( dict, "d" , { get: function () { return ++ x; } }); Object. defineProperty( dict, "c" , { get: function () { return ++ x; } }); something. f( dict);
The order that the dictionary members are fetched in determines what values they will be taken to have. Since the order forA is defined to be c then d, the value for c will be 1 and the value for d will be 2.
The identifier of a dictionary member must not bethe same as that of another dictionary member defined on the dictionary oron that dictionary’sinherited dictionaries.
Dictionaries must not be used as the type of anattribute orconstant.
Noextended attributes are applicable to dictionaries.
Partial ::partial PartialDefinition
Dictionary ::dictionary identifier Inheritance { DictionaryMembers } ;
DictionaryMembers ::DictionaryMember DictionaryMembers ε
DictionaryMember ::ExtendedAttributeList DictionaryMemberRest
DictionaryMemberRest ::required TypeWithExtendedAttributes identifier ; Type identifier Default ;
PartialDictionary ::dictionary identifier { DictionaryMembers } ;
Default ::= DefaultValue ε
DefaultValue ::ConstValue string [ ] { } null
Inheritance ::: identifier ε
One use of dictionary types is to allow a number of optional arguments to anoperation without being constrained as to the order they are specified at the call site. For example, consider the followingIDL fragment:
[Exposed =Window ]interface Point {constructor ();attribute double x ;attribute double y ;};dictionary PaintOptions {DOMString ?fillPattern = "black";DOMString ?strokePattern =null ;Point position ;};[Exposed =Window ]interface GraphicsContext {void drawRectangle (double width ,double height ,optional PaintOptions options );};
In an ECMAScript implementation of the IDL, an Object can be passed in for the optionalPaintOptions dictionary:
// Get an instance of GraphicsContext. var ctx= getGraphicsContext(); // Draw a rectangle. ctx. drawRectangle( 300 , 200 , { fillPattern: "red" , position: new Point( 10 , 10 ) });
Both fillPattern and strokePattern are givendefault values, so if they are omitted, the definition of drawRectangle can assume that they have the given default values and not include explicit wording to handle their non-presence.
2.8.Exceptions
Anexception is a type of object thatrepresents an error and which can be thrown or treated as a firstclass value by implementations. Web IDL does not allow exceptionsto be defined, but instead has a number of pre-defined exceptionsthat specifications can reference and throw in their definition ofoperations, attributes, and so on. Exceptions have anerror name,aDOMString,which is the type of error the exception represents, and amessage, which is an optional,user agent-defined value that provides human readable details of the error.
There are two kinds of exceptions available to be thrown from specifications.The first is asimple exception, whichis identified by one of the following types:
These correspond to all of the ECMAScripterror objects (apart fromSyntaxError andError,which are deliberately omitted as they are reserved for useby the ECMAScript parser and by authors, respectively).The meaning of eachsimple exception matchesits corresponding error object in theECMAScript specification.
The second kind of exception is aDOMException,which is an exception that encapsulates a name and an optional integer code,for compatibility with historically defined exceptions in the DOM.
Forsimple exceptions, theerror name is the type of the exception.For aDOMException, theerror name must be one of the nameslisted in theerror names table below.The table also indicates theDOMException's integer code for that error name,if it has one.
Note: AsDOMException is aninterface type, it can be used as a type in IDL.This allows for example anoperation to be declared to have aDOMExceptionreturn type.
Simple exceptions can becreated by providing theirerror name.ADOMException can becreated by providing itserror name followed byDOMException.Exceptions can also bethrown, by providing thesame details required tocreate one.
The resulting behavior from creating and throwing an exception is language binding-specific.
Note: See§ 3.12.3 Creating and throwing exceptions for details on what creating and throwing an exceptionentails in the ECMAScript language binding.
Here is are some examples of wording to use to create and throw exceptions. To throw a newsimple exception namedTypeError:
Throw aTypeError.To throw a newDOMException witherror name "NotAllowedError":
Throw an "NotAllowedError"DOMException.
To create a newDOMException witherror name "SyntaxError":
Letobject be a newlycreated "SyntaxError"DOMException.
2.8.1.Error names
Theerror names table below lists all the allowed error namesforDOMException, a description, and legacy code values.
TheDOMException names marked as deprecated are kept for legacy purposes but their usage is discouraged.
Note: If an error name is not listed here, please file a bug as indicated at the top of this specification and it will be addressed shortly. Thanks!
Note: Don’t confuse the "SyntaxError"DOMException defined herewith ECMAScript’sSyntaxError."SyntaxError"DOMException is used to report parsing errors in web APIs,for example when parsing selectors,while the ECMAScriptSyntaxError is reserved for the ECMAScript parser.To help disambiguate this further,always favor the "SyntaxError"DOMException notationover just usingSyntaxError to refer to theDOMException.[DOM]
| Name | Description | Legacy code name and value |
|---|---|---|
"IndexSizeError" | Deprecated. UseRangeError instead. | INDEX_SIZE_ERR (1) |
"DOMStringSizeError" | Deprecated. UseRangeError instead. | DOMSTRING_SIZE_ERR (2) |
"HierarchyRequestError" | The operation would yield an incorrectnode tree.[DOM] | HIERARCHY_REQUEST_ERR (3) |
"WrongDocumentError" | The object is in the wrongdocument.[DOM] | WRONG_DOCUMENT_ERR (4) |
"InvalidCharacterError" | The string contains invalid characters. | INVALID_CHARACTER_ERR (5) |
"NoDataAllowedError" | Deprecated. | NO_DATA_ALLOWED_ERR (6) |
"NoModificationAllowedError" | The object can not be modified. | NO_MODIFICATION_ALLOWED_ERR (7) |
"NotFoundError" | The object can not be found here. | NOT_FOUND_ERR (8) |
"NotSupportedError" | The operation is not supported. | NOT_SUPPORTED_ERR (9) |
"InUseAttributeError" | The attribute is in use. | INUSE_ATTRIBUTE_ERR (10) |
"InvalidStateError" | The object is in an invalid state. | INVALID_STATE_ERR (11) |
"SyntaxError" | The string did not match the expected pattern. | SYNTAX_ERR (12) |
"InvalidModificationError" | The object can not be modified in this way. | INVALID_MODIFICATION_ERR (13) |
"NamespaceError" | The operation is not allowed byNamespaces in XML.[XML-NAMES] | NAMESPACE_ERR (14) |
"InvalidAccessError" | Deprecated. UseTypeError for invalid arguments, "NotSupportedError"DOMException for unsupported operations, and "NotAllowedError"DOMException for denied requests instead. | INVALID_ACCESS_ERR (15) |
"ValidationError" | Deprecated. | VALIDATION_ERR (16) |
"TypeMismatchError" | Deprecated. UseTypeError instead. | TYPE_MISMATCH_ERR (17) |
"SecurityError" | The operation is insecure. | SECURITY_ERR (18) |
"NetworkError" | A network error occurred. | NETWORK_ERR (19) |
"AbortError" | The operation was aborted. | ABORT_ERR (20) |
"URLMismatchError" | The given URL does not match another URL. | URL_MISMATCH_ERR (21) |
"QuotaExceededError" | The quota has been exceeded. | QUOTA_EXCEEDED_ERR (22) |
"TimeoutError" | The operation timed out. | TIMEOUT_ERR (23) |
"InvalidNodeTypeError" | The supplied node is incorrect or has an incorrect ancestor for this operation. | INVALID_NODE_TYPE_ERR (24) |
"DataCloneError" | The object can not be cloned. | DATA_CLONE_ERR (25) |
"EncodingError" | The encoding operation (either encoded or decoding) failed. | — |
"NotReadableError" | The I/O read operation failed. | — |
"UnknownError" | The operation failed for an unknown transient reason (e.g. out of memory). | — |
"ConstraintError" | A mutation operation in a transaction failed because a constraint was not satisfied. | — |
"DataError" | Provided data is inadequate. | — |
"TransactionInactiveError" | A request was placed against a transaction which is currently not active, or which is finished. | — |
"ReadOnlyError" | The mutating operation was attempted in a "readonly" transaction. | — |
"VersionError" | An attempt was made to open a database using a lower version than the existing version. | — |
"OperationError" | The operation failed for an operation-specific reason. | — |
"NotAllowedError" | The request is not allowed by the user agent or the platform in the current context, possibly because the user denied permission. | — |
2.9.Enumerations
Anenumeration is a definition (matchingDOMString values that can be assigned to anattribute or passed to anoperation.
enum identifier {"enum" ,"values" /* , ... */ };
Theenumeration values are specifiedas a comma-separated list of
It is strongly suggested that enumeration values be all lowercase, and that multiple words be separated using dashes or not be separated at all, unless there is a specific reason to use another value naming scheme. For example, an enumeration value that indicates an object should be created could be named "createobject" or "create-object". Consider related uses of enumeration values when deciding whether to dash-separate or not separate enumeration value words so that similar APIs are consistent.
The behavior when a string value that is not one a valid enumeration valueis used when assigning to anattribute,or passed as anoperation argument,whose type is the enumeration, is language binding specific.
Note: In the ECMAScript binding, assignment of an invalid string value to anattribute is ignored, whilepassing such a value in other contexts (for example as anoperation argument)results in an exception being thrown.
Noextended attributes defined in this specification are applicable toenumerations.
Enum ::enum identifier { EnumValueList } ;
EnumValueList ::string EnumValueListComma
EnumValueListComma ::, EnumValueListString ε
EnumValueListString ::string EnumValueListComma ε
The followingIDL fragment defines anenumeration that is used as the type of anattribute and anoperation argument:
enum MealType {"rice" ,"noodles" ,"other" };[Exposed =Window ]interface Meal {attribute MealType type ;attribute double size ; // in gramsvoid initialize (MealType type ,double size );};
An ECMAScript implementation would restrict the strings that can be assigned to the type property or passed to the initializeMeal function to those identified in theenumeration.
var meal= getMeal(); // Get an instance of Meal. meal. initialize( "rice" , 200 ); // Operation invoked as normal. try { meal. initialize( "sandwich" , 100 ); // Throws a TypeError. } catch ( e) { } meal. type= "noodles" ; // Attribute assigned as normal. meal. type= "dumplings" ; // Attribute assignment ignored. meal. type== "noodles" ; // Evaluates to true.
2.10.Callback functions
The “Custom DOM Elements” spec wants to use callback function types for platform object provided functions. Should we rename “callback functions” to just “functions” to make it clear that they can be used for both purposes?
Acallback function is a definition (matching
callback identifier =return_type (/* arguments... */);
Note: See also the similarly namedcallback interfaces.
Theidentifier on theleft of the equals sign gives the name of thecallback function and the return type and argument list (matching
Callback functions must notbe used as the type of aconstant.
The following extended attribute is applicable to callback functions:[TreatNonObjectAsNull].
CallbackOrInterfaceOrMixin ::callback CallbackRestOrInterface interface InterfaceOrMixin
CallbackRest ::identifier = ReturnType ( ArgumentList ) ;
The followingIDL fragment defines acallback function used for an API that invokes a user-defined function when an operation is complete.
callback AsyncOperationCallback =void (DOMString status );[Exposed =Window ]interface AsyncOperations {void performOperation (AsyncOperationCallback whenFinished );};
In the ECMAScript language binding, afunction object is passed as the operation argument.
var ops= getAsyncOperations(); // Get an instance of AsyncOperations. ops. performOperation( function ( status) { window. alert( "Operation finished, status is " + status+ "." ); });
2.11.Typedefs
Atypedef is a definition (matching
typedef type identifier ;
Thetype being given a new name is specified after the
The
Noextended attributes defined in this specification are applicable totypedefs.
Typedef ::typedef TypeWithExtendedAttributes identifier ;
The followingIDL fragment demonstrates the use oftypedefs to allow the use of a shortidentifier instead of a longsequence type.
[Exposed =Window ]interface Point {attribute double x ;attribute double y ;};typedef sequence <Point >Points ;[Exposed =Window ]interface Widget {boolean pointWithinBounds (Point p );boolean allPointsWithinBounds (Points ps );};
2.12.Objects implementing interfaces
In a given implementation of a set ofIDL fragments,an object can be described as being aplatform object.
Platform objects are objectsthat implement aninterface.
Legacy platform objects areplatform objects that implement aninterface whichdoes not have a [Global]extended attribute, and whichsupports indexed properties,named properties, or both.
In a browser, for example,the browser-implemented DOM objects (implementing interfaces such asNode andDocument) that provide access to a web page’s contentsto ECMAScript running in the page would beplatform objects. These objects might be exotic objects,implemented in a language like C++, or they might be native ECMAScript objects. Regardless,an implementation of a given set of IDL fragments needs to be able to recognize allplatform objects that are created by the implementation. This might be done by having some internal state that records whethera given object is indeed a platform object for that implementation, or perhaps by observingthat the object is implemented by a given internal C++ class. How exactly platform objectsare recognized by a given implementation of a set of IDL fragments is implementation specific.
All other objects in the system would not be treated as platform objects. For example, assume thata web page opened in a browser loads an ECMAScript library that implements DOM Core. This librarywould be considered to be a different implementation from the browser provided implementation.The objects created by the ECMAScript library that implement theNode interfacewill not be treated as platform objects that implementNode by the browser implementation.
Callback interfaces, on the other hand, can be implemented by any ECMAScript object. Thisallows Web APIs to invoke author-defined operations. For example, the DOM Events implementationallows authors to register callbacks by providing objects that implement theEventListener interface.
2.13.Types
This section lists the types supported by Web IDL, the set of valuescorresponding to each type, and howconstants of that type are represented.
The following types are known asinteger types:byte,octet,short,unsigned short,long,unsigned long,long long andunsigned long long.
The following types are known asnumeric types:theinteger types,float,unrestricted float,double andunrestricted double.
Theprimitive types areboolean and thenumeric types.
Thestring types areDOMString, allenumeration types,ByteString andUSVString.
Thetyped array types areInt8Array,Int16Array,Int32Array,Uint8Array,Uint16Array,Uint32Array,Uint8ClampedArray,Float32Array andFloat64Array.
Thebuffer source types areArrayBuffer,DataView,and thetyped array types.
Theobject type,allinterface types, andallcallback interface types are known asobject types.
Every type has atype name, whichis a string, not necessarily unique, that identifies the type.Each sub-section below defines what the type name is for eachtype.
When conversions are made from language binding specific types to IDL types in order to invoke anoperation or assign a value to anattribute, all conversions necessary will be performed before the specified functionality of the operation or attribute assignment is carried out. If the conversion cannot be performed, then the operation will not run or the attribute will not be updated. In some language bindings, type conversions could result in an exception being thrown. In such cases, these exceptions will be propagated to the code that made the attempt to invoke the operation or assign to the attribute.
Type ::SingleType UnionType Null
TypeWithExtendedAttributes ::ExtendedAttributeList Type
SingleType ::DistinguishableType any PromiseType
UnionType ::( UnionMemberType or UnionMemberType UnionMemberTypes )
UnionMemberType ::ExtendedAttributeList DistinguishableType UnionType Null
UnionMemberTypes ::or UnionMemberType UnionMemberTypes ε
DistinguishableType ::PrimitiveType Null StringType Null identifier Null sequence < TypeWithExtendedAttributes > Null object Null symbol Null BufferRelatedType Null FrozenArray < TypeWithExtendedAttributes > Null RecordType Null
PrimitiveType ::UnsignedIntegerType UnrestrictedFloatType boolean byte octet
UnrestrictedFloatType ::unrestricted FloatType FloatType
FloatType ::float double
UnsignedIntegerType ::unsigned IntegerType IntegerType
IntegerType ::short long OptionalLong
OptionalLong ::long ε
StringType ::ByteString DOMString USVString
PromiseType ::Promise < ReturnType >
RecordType ::record < StringType , TypeWithExtendedAttributes >
Null ::? ε
2.13.1.any
Theany type is the union of all other possiblenon-union types.Itstype name is "Any".
Theany type is likea discriminated union type, in that each of its values has aspecific non-any typeassociated with it. For example, one value of theany type is theunsigned long 150, while another is thelong 150.These are distinct values.
The particular type of anany value is known as itsspecific type.(Values ofunion types also havespecific types.)
2.13.2.void
Thevoid type has a unique value.
It can only be used as thereturn type of anoperation or the parameter of apromise type.
Thetype name of thevoid type is "Void".
2.13.3.boolean
Theboolean type has two values:true andfalse.
boolean constant values in IDL arerepresented with the
Thetype name of theboolean type is "Boolean".
2.13.4.byte
Thebyte type is a signed integertype that has values in the range [−128, 127].
byte constant values in IDL arerepresented with
Thetype name of thebyte type is "Byte".
2.13.5.octet
Theoctet type is an unsigned integertype that has values in the range [0, 255].
octet constant values in IDL arerepresented with
Thetype name of theoctet type is "Octet".
2.13.6.short
Theshort type is a signed integertype that has values in the range [−32768, 32767].
short constant values in IDL arerepresented with
Thetype name of theshort type is "Short".
2.13.7.unsigned short
Theunsigned short type is an unsigned integertype that has values in the range [0, 65535].
unsigned short constant values in IDL arerepresented with
Thetype name of theunsigned short type is "UnsignedShort".
2.13.8.long
Thelong type is a signed integertype that has values in the range [−2147483648, 2147483647].
long constant values in IDL arerepresented with
Thetype name of thelong type is "Long".
2.13.9.unsigned long
Theunsigned long type is an unsigned integertype that has values in the range [0, 4294967295].
unsigned long constant values in IDL arerepresented with
Thetype name of theunsigned long type is "UnsignedLong".
2.13.10.long long
Thelong long type is a signed integertype that has values in the range [−9223372036854775808, 9223372036854775807].
long long constant values in IDL arerepresented with
Thetype name of thelong long type is "LongLong".
2.13.11.unsigned long long
Theunsigned long long type is an unsigned integertype that has values in the range [0, 18446744073709551615].
unsigned long long constant values in IDL arerepresented with
Thetype name of theunsigned long long type is "UnsignedLongLong".
2.13.12.float
Thefloat type is a floating point numerictype that corresponds to the set of finite single-precision 32 bitIEEE 754 floating point numbers.[IEEE-754]
float constant values in IDL arerepresented with
Thetype name of thefloat type is "Float".
Unless there are specific reasons to use a 32 bit floating point type, specifications should usedouble rather thanfloat, since the set of values that adouble can represent more closely matches an ECMAScript Number.
2.13.13.unrestricted float
Theunrestricted float type is a floating point numerictype that corresponds to the set of all possible single-precision 32 bitIEEE 754 floating point numbers, finite, non-finite, and special "not a number" values (NaNs).[IEEE-754]
unrestricted float constant values in IDL arerepresented with
Thetype name of theunrestricted float type is "UnrestrictedFloat".
2.13.14.double
Thedouble type is a floating point numerictype that corresponds to the set of finite double-precision 64 bitIEEE 754 floating point numbers.[IEEE-754]
double constant values in IDL arerepresented with
Thetype name of thedouble type is "Double".
2.13.15.unrestricted double
Theunrestricted double type is a floating point numerictype that corresponds to the set of all possible double-precision 64 bitIEEE 754 floating point numbers, finite, non-finite, and special "not a number" values (NaNs).[IEEE-754]
unrestricted double constant values in IDL arerepresented with
Thetype name of theunrestricted double type is "UnrestrictedDouble".
2.13.16.DOMString
TheDOMString type corresponds tothe set of all possible sequences ofcode units.Such sequences are commonly interpreted as UTF-16 encoded strings[RFC2781] although this is not required.WhileDOMString is defined to bean OMG IDL boxedsequence<unsigned short> valuetypeinDOM Level 3 Core §The DOMString Type,this document definesDOMString to be an intrinsic typeso as to avoid special casing that sequence typein various situations where a string is required.
Note: Note also thatDOMString.To allowDOMString,written asDOMString? in IDL, needs to be used.
Nothing in this specification requires aDOMString value to be a valid UTF-16 string. For example, aDOMString value might include unmatched surrogate pair characters. However, authorsof specifications using Web IDL might want to obtain a sequence ofUnicode scalar values given a particular sequence ofcode units.
The following algorithm defines a way toconvert a DOMString to a sequence of Unicode scalar values:
LetS be the
DOMStringvalue.Letn be the length ofS.
Initializei to 0.
InitializeU to be an empty sequence of Unicode characters.
Whilei <n:
Letc be thecode unit inS at indexi.
Depending on the value ofc:
- c < 0xD800 orc > 0xDFFF
Append toU the Unicode character with code pointc.
- 0xDC00 ≤c ≤ 0xDFFF
Append toU aU+FFFD REPLACEMENT CHARACTER.
- 0xD800 ≤c ≤ 0xDBFF
Ifi =n−1, then append toU aU+FFFD REPLACEMENT CHARACTER.
Otherwise,i <n−1:
Letd be the code unit inS at indexi+1.
If 0xDC00 ≤d ≤ 0xDFFF, then:
Leta bec & 0x3FF.
Letb bed & 0x3FF.
Append toU the Unicode character withcode point 216+210a+b.
Seti toi+1.
Otherwise,d < 0xDC00 ord > 0xDFFF.Append toU aU+FFFD REPLACEMENT CHARACTER.
Seti toi+1.
ReturnU.
There is no way to represent a constantDOMString value in IDL, althoughDOMStringdictionary memberdefault values andoperation optional argumentdefault values can be set tothe value of a
Thetype name of theDOMString type is "String".
2.13.17.ByteString
TheByteString typecorresponds to the set of all possible sequences of bytes.Such sequences might be interpreted as UTF-8 encoded strings[RFC3629] or strings in some other 8-bit-per-code-unit encoding, although this is not required.
There is no way to represent a constantByteString value in IDL, althoughByteStringdictionary memberdefault values andoperation optional argumentdefault values can be set tothe value of a
Thetype name of theByteString type is "ByteString".
Specifications should only useByteString for interfacing with protocols that use bytes and strings interchangeably, such as HTTP. In general, strings should be represented withDOMString values, even if it is expected that values of the string will always be in ASCII or some 8 bit character encoding.Sequences orfrozen arrays withoctet orbyte elements,Uint8Array, orInt8Array should be used for holding 8 bit data rather thanByteString.
2.13.18.USVString
TheUSVString typecorresponds to the set of all possible sequences ofUnicode scalar values,which are all of the Unicode code points apart from thesurrogate code points.
There is no way to represent a constantUSVString value in IDL, althoughUSVStringdictionary memberdefault values andoperation optional argumentdefault values can be set tothe value of a
Thetype name of theUSVString type is "USVString".
Specifications should only useUSVString for APIs that perform text processing and need a string of Unicode scalar values to operate on. Most APIs that use strings should instead be usingDOMString, which does not make any interpretations of thecode units in the string. When in doubt, useDOMString.
2.13.19.object
Theobject type corresponds to the set ofall possible non-null object references.
There is no way to represent a constantobject value in IDL.
To denote a type that includes all possible object references plus theobject?.
Thetype name of theobject type is "Object".
2.13.20.symbol
Thesymbol type corresponds to the set of all possible symbol values. Symbol values are opaque,non-object values which nevertheless have identity (i.e., are only equal to themselves).
There is no way to represent a constantsymbol value in IDL.
Thetype name of thesymbol type is "Symbol".
2.13.21.Interface types
Anidentifier thatidentifies aninterface is used to refer toa type that corresponds to the set of all possible non-null references to objects thatimplement that interface.
An IDL value of the interface type is represented justby an object reference.
There is no way to represent a constant object reference value fora particular interface type in IDL.
To denote a type that includes all possible references to objects implementingthe given interface plus the
Thetype name of an interface typeis theidentifier of the interface.
2.13.22.Callback interface types
Anidentifier that identifies acallback interface is used to refer to a type thatcorresponds to the set of all possible non-null references to objects.
An IDL value of the interface type is represented by a tuple of an object reference and acallback context.Thecallback context is a language binding specific value, and is used to store informationabout the execution context at the time the language binding specific object reference isconverted to an IDL value.
Note: For ECMAScript objects, thecallback context is used to hold a reference to theincumbent settings object at the time the Object value is converted to an IDL callbackinterface type value. See§ 3.2.15 Callback interface types.
There is no way to represent a constant object reference value for a particularcallback interface type in IDL.
To denote a type that includes all possible references to objects plus the
Thetype name of acallback interface type is theidentifier of thecallback interface.
2.13.23.Dictionary types
Anidentifier thatidentifies adictionary is used to refer toa type that corresponds to the set of all dictionaries that adhere tothe dictionary definition.
The literal syntax forordered maps may also be used to represent dictionaries, when it isimplicitly understood from context that the map is being treated as an instance of a specificdictionary type. However, there is no way to represent a constant dictionary value inside IDLfragments.
Thetype name of a dictionary typeis theidentifier of the dictionary.
2.13.24.Enumeration types
Anidentifier thatidentifies anenumeration is used torefer to a type whose values are the set of strings (sequences ofcode units, as withDOMString) that are theenumeration’s values.
LikeDOMString, there is no way to represent a constantenumeration value in IDL, although enumeration-typeddictionary memberdefault values andoperation optional argumentdefault values can be set tothe value of a
Thetype name of an enumeration typeis theidentifier of the enumeration.
2.13.25.Callback function types
Anidentifier that identifiesacallback function is used to refer toa type whose values are references to objects that are functions with the given signature.
An IDL value of the callback function type is represented by a tuple of an objectreference and acallback context.
Note: As withcallback interface types, thecallback context is used to hold areference to theincumbent settings object atthe time an ECMAScript Object value is converted to an IDLcallback function type value. See§ 3.2.18 Callback function types.
There is no way to represent a constantcallback function value in IDL.
Thetype name of a callback function typeis theidentifier of the callback function.
2.13.26.Nullable types —T?
Anullable type is an IDL type constructedfrom an existing type (called theinner type),which just allows the additional value
any,another nullable type, or
aunion type that itselfincludes a nullable type or has a dictionary type as one of itsflattened member types.
Note: Although dictionary types can in general be nullable,they cannot when used as the type of an operation argument or a dictionary member.
Nullable type constant values in IDL are represented in the same way thatconstant values of theirinner type would be represented, or with the
Thetype name of a nullable typeis the concatenation of the type name of theinner typeT andthe string "OrNull".
For example, a type that allows the valuesboolean?:
[Exposed =Window ]interface NetworkFetcher {void get (optional boolean ?areWeThereYet =false );};
The followinginterface has twoattributes: one whose value can be aDOMString or theNode object or the
[Exposed =Window ]interface Node {readonly attribute DOMString ?namespaceURI ;readonly attribute Node ?parentNode ; // ...};
2.13.27.Sequence types — sequence<T>
Thesequence<T> type is a parameterized type whose values are (possibly zero-length)lists ofvalues of typeT.
Sequences are always passed by value. Inlanguage bindings where a sequence is represented by an object ofsome kind, passing a sequence to aplatform object will not result in a reference to the sequence being kept by that object.Similarly, any sequence returned from a platform objectwill be a copy and modifications made to it will not be visible to the platform object.
The literal syntax forlists may also be used to represent sequences, when it is implicitlyunderstood from context that the list is being treated as a sequences. However, there is no way torepresent a constant sequence value inside IDL fragments.
Sequences must not be used as thetype of anattribute orconstant.
Note: This restriction exists so that it is clear to specification writersand API users thatsequences are copied rather than having referencesto them passed around. Instead of a writableattribute of a sequencetype, it is suggested that a pair ofoperations to get and set thesequence is used.
Thetype name of a sequence typeis the concatenation of the type name forT andthe string "Sequence".
Anylist can be implicitly treated as asequence<T>, as long as it containsonlyitems that are of typeT.
2.13.28.Record types — record<K,V>
Arecord type is a parameterized type whose values areordered maps withkeys that are instances ofK andvalues that are instances ofV.K must be oneofDOMString,USVString, orByteString.
The literal syntax forordered maps may also be used to represent records, when it is implicitlyunderstood from context that the map is being treated as a record. However, there is no way torepresent a constant record value inside IDL fragments.
Records are always passed by value. In language bindings where a recordis represented by an object of some kind, passing a recordto aplatform object will not result in a reference to the recordbeing kept by that object. Similarly, any record returned from aplatform object will be a copy and modifications made to it will not be visibleto the platform object.
Records must not be used as the type of anattribute orconstant.
Thetype name of a record type is the concatenation of the typename forK, the type name forV and the string "Record".
Anyordered map can be implicitly treated as arecord<K,V>, as long asit contains onlyentries whosekeys are all of of typeK and whosevalues are all of typeV.
2.13.29.Promise types — Promise<T>
Apromise type is a parameterized typewhose values are references to objects that “is used as a place holderfor the eventual results of a deferred (and possibly asynchronous) computationresult of an asynchronous operation”.Seesection 25.4 of the ECMAScript specification for details on the semantics of promise objects.
Promise types are non-nullable, butT may be nullable.
There is no way to represent a promise value in IDL.
Thetype name of a promise typeis the concatenation of the type name forT andthe string "Promise".
2.13.30.Union types
Aunion type is a type whose set of valuesis the union of those in two or more other types. Union types (matching
For example, you might write(Node or DOMString) or(double or sequence<double>). When applying a(Node or DOMString)?.
Note that themember types of a union type do not descend into nested union types. So for(double or (sequence<long> or Event) or (Node or DOMString)?) the member types aredouble,(sequence<long> or Event) and(Node or DOMString)?.
Like theany type, values ofunion types have aspecific type,which is the particularmember type that matches the value.
Theflattened member types of aunion type, possiblyannotated, is a set of types determined as follows:
LetT be theunion type.
InitializeS to ∅.
For eachmember typeU ofT:
IfU is anannotated type, thensetU to be theinner type ofU.
IfU is anullable type, thensetU to be theinner type ofU.
IfU is aunion type, thenadd toS theflattened member types ofU.
Otherwise,U is not aunion type.AddU toS.
ReturnS.
Note: For example, theflattened member types of theunion type(Node or (sequence<long> or Event) or (XMLHttpRequest or DOMString)? or sequence<(sequence<double> or NodeList)>) are the six typesNode,sequence<long>,Event,XMLHttpRequest,DOMString andsequence<(sequence<double> or NodeList)>.
Thenumber of nullable member types of aunion type is an integer determined as follows:
LetT be theunion type.
Initializen to 0.
For eachmember typeU ofT:
IfU is anullable type, then:
Setn ton + 1.
SetU to be theinner type ofU.
IfU is aunion type, then:
Letm be thenumber of nullable member types ofU.
Setn ton +m.
Returnn.
Theany type must notbe used as aunion member type.
Thenumber of nullable member types of aunion type mustbe 0 or 1, and if it is 1 then the union type must also not haveadictionary type in itsflattened member types.
A typeincludes a nullable type if:
the type is anullable type, or
the type is anannotated type and itsinner type is a nullable type, or
the type is aunion type and itsnumber of nullable member types is 1.
Each pair offlattened member types in aunion type,T andU,must bedistinguishable.
Union type constant valuesin IDL are represented in the same way that constant values of theirmember types would berepresented.
Thetype name of a uniontype is formed by taking the type names of each member type, in order,and joining them with the string "Or".
DistinguishableType ::PrimitiveType Null StringType Null identifier Null sequence < TypeWithExtendedAttributes > Null object Null symbol Null BufferRelatedType Null FrozenArray < TypeWithExtendedAttributes > Null RecordType Null
2.13.31.Annotated types
Additional types can be created from existing ones by specifying certainextended attributes onthe existing types. Such types are calledannotated types, and the types theyannotate are calledinner types.
[Clamp] long defines a newannotated type, whose behavior is based on that of theinner typelong, but modified as specified by the [Clamp] extended attribute.The following extended attributes areapplicable to types:[AllowShared],[Clamp],[EnforceRange], and[TreatNullAs].
Letextended attributes be a new emptyset.
Iftype appears as part of a
TypeWithExtendedAttributes production,append each of theextended attributes present in the production’sExtendedAttributeList toextended attributes.Iftype is amember type of aunion typeU,append each of theextended attributes associated withU toextended attributes.
Iftype appears as part of a
Type productiondirectly within anArgument production,append toextended attributes all of theextended attributes present in theproduction’sExtendedAttributeList that areapplicable to types.[
Exposed =Window ]interface I {void f ([XAttr ]long attrib );};Note that this is an example of this step only if [
XAttr] isapplicable to types; otherwise [XAttr] applies to the argument, and not the argument’s type.Iftype appears as part of a
Type productiondirectly within anDictionaryMember production,append toextended attributes all of theextended attributes present in the production’sExtendedAttributeList that areapplicable to types.dictionary D { [XAttr ]long member ;};Note that this is an example of this step only if [
XAttr] isapplicable to types; otherwise [XAttr] applies to the dictionary member, and not the member’s type.Iftype is atypedef,append theextended attributes associated with thetype being given a new name toextended attributes.
Returnextended attributes.
For any type, theextended attributes associated with it must only containextended attributes that areapplicable to types.
Thetype name of a type associated withextended attributes is the concatenation of thetype name of the original type with the set of strings corresponding to theidentifiers of eachextended attribute associated with the type, sorted in lexicographic order.
2.13.32.Buffer source types
There are a number of types that correspond to sets of all possible non-nullreferences to objects that represent a buffer of data or a view on to a buffer ofdata. The table below lists these types and the kind of buffer or view they represent.
| Type | Kind of buffer |
|---|---|
ArrayBuffer | An object that holds a pointer (which may be null) to a buffer of a fixed number of bytes |
DataView | A view on to anArrayBuffer that allows typed access to integers and floating point values stored at arbitrary offsets into the buffer |
Int8Array,Int16Array,Int32Array | A view on to anArrayBuffer that exposes it as an array of two’s complement signed integers of the given size in bits |
Uint8Array,Uint16Array,Uint32Array | A view on to anArrayBuffer that exposes it as an array of unsigned integers of the given size in bits |
Uint8ClampedArray | A view on to anArrayBuffer that exposes it as an array of unsigned 8 bit integers with clamped conversions |
Float32Array,Float64Array | A view on to anArrayBuffer that exposes it as an array of IEEE 754 floating point numbers of the given size in bits |
Note: These types all correspond to classes defined in ECMAScript.
There is no way to represent a constant value of any of these types in IDL.
Thetype name of allof these types is the name of the type itself.
At the specification prose level, IDLbuffer source types are simply references to objects. To inspect or manipulate the bytes inside the buffer,specification prose must first eitherget a reference to the bytes held by the buffer source orget a copy of the bytes held by the buffer source.With a reference to the buffer source’s bytes, specification prose can get or set individualbyte values using that reference.
Extreme care must be taken when writing specification text that gets a reference to the bytes held by a buffer source, as the underlying data can easily be changed by the script author or other APIs at unpredictable times. If you are using a buffer source type as an operation argument to obtain a chunk of binary data that will not be modified, it is strongly recommended to get a copy of the buffer source’s bytes at the beginning of the prose defining the operation.
Requiring prose to explicitly get a reference to or copy of the bytes is intended to help specification reviewers look for problematic uses of these buffer source types.
When designing APIs that take a buffer, it is recommended to use theBufferSource typedef rather thanArrayBuffer or any of the view types.
When designing APIs that create and return a buffer, it is recommended to use theArrayBuffer type rather thanUint8Array.
Attempting toget a reference to orget a copy of the bytes held by a buffer source when theArrayBuffer has beendetached will fail in a language binding-specific manner.
Note: See§ 3.2.24 Buffer source types below forhow interacting with buffer source types works in the ECMAScript language binding.
We should include an example of specification text that uses these types and terms.
BufferRelatedType ::ArrayBuffer DataView Int8Array Int16Array Int32Array Uint8Array Uint16Array Uint32Array Uint8ClampedArray Float32Array Float64Array
2.13.33.Frozen array types — FrozenArray<T>
Afrozen array type is a parameterizedtype whose values are references to objects that hold a fixed length arrayof unmodifiable values. The values in the array are of typeT.
SinceFrozenArray<T> valuesare references, they are unlikesequence types,which are lists of values that are passed by value.
There is no way to represent a constant frozen array value in IDL.
Thetype name of a frozen arraytype is the concatenation of the type name forT and the string"Array".
2.14.Extended attributes
Anextended attribute is an annotationthat can appear ondefinitions,types asannotated types,interface members,interface mixin members,callback interface members,namespace members,dictionary members,andoperation arguments, andis used to control how language bindings will handle those constructs.Extended attributes are specified with an
The
| Grammar symbol | Form | Example |
|---|---|---|
| takes no arguments | [Replaceable] | |
| takes an argument list | Not currently used; previously used by[Constructor(double x, double y)] | |
| takes a named argument list | [NamedConstructor=Image(DOMString src)] | |
| takes an identifier | [PutForwards=name] | |
| takes an identifier list | [Exposed=(Window,Worker)] |
This specification defines a number of extended attributes thatare applicable to the ECMAScript language binding, which are described in§ 3.3 ECMAScript-specific extended attributes.Each extended attribute definition will state which of the abovefive forms are allowed.
ExtendedAttributeList ::[ ExtendedAttribute ExtendedAttributes ] ε
ExtendedAttributes ::, ExtendedAttribute ExtendedAttributes ε
ExtendedAttribute ::( ExtendedAttributeInner ) ExtendedAttributeRest [ ExtendedAttributeInner ] ExtendedAttributeRest { ExtendedAttributeInner } ExtendedAttributeRest Other ExtendedAttributeRest
ExtendedAttributeRest ::ExtendedAttribute ε
ExtendedAttributeInner ::( ExtendedAttributeInner ) ExtendedAttributeInner [ ExtendedAttributeInner ] ExtendedAttributeInner { ExtendedAttributeInner } ExtendedAttributeInner OtherOrComma ExtendedAttributeInner ε
Other ::integer decimal identifier string other - -Infinity . ... : ; < = > ? ByteString DOMString FrozenArray Infinity NaN Promise USVString any boolean byte double false float long null object octet or optional record sequence short symbol true unsigned void ArgumentNameKeyword BufferRelatedType
OtherOrComma ::Other ,
IdentifierList ::identifier Identifiers
Identifiers ::, identifier Identifiers ε
ExtendedAttributeNoArgs ::identifier
ExtendedAttributeArgList ::identifier ( ArgumentList )
ExtendedAttributeIdent ::identifier = identifier
ExtendedAttributeIdentList ::identifier = ( IdentifierList )
ExtendedAttributeNamedArgList ::identifier = identifier ( ArgumentList )
3.ECMAScript binding
This section describes how definitions written with the IDL defined in§ 2 Interface definition language correspond to particular constructsin ECMAScript, as defined by theECMAScript Language Specification[ECMA-262].
Unless otherwise specified, objects defined in this section are ordinary objects as described inECMA-262 Ordinary object internal methods and internal slots, and if theobject is afunction object,ECMA-262 Built-in function objects.
This section may redefine certain internal methods and/or internal slots of objects. Otherspecifications may also override the definitions of any internal method and/or internal slots of aplatform object that is an instance of aninterface. These objects with changed semanticsshall be treated in accordance with the rules for exotic objects.
As overriding internal ECMAScript object methods is a low level operation and can result in objects that behave differently from ordinary objects, this facility should not be used unless necessary for security or compatibility.This is currently used to define theHTMLAllCollection andLocation interfaces.[HTML]
Unless otherwise specified, exotic objects defined in this section and other specifications have thesameinternal slots as ordinary objects, and all of the internal methods forwhich alternative definitions are not given are the same asthose of ordinary objects.
Unless otherwise specified, the [[Extensible]] internal slotof objects defined in this section has the value
Unless otherwise specified, the [[Prototype]] internal slotof objects defined in this section is%ObjectPrototype%.
Some objects described in this section are defined to have aclass string,which is the string to include in the string returned from Object.prototype.toString.
If an object has aclass stringclassString, then the object must,at the time it is created, have a property whose name is the@@toStringTag symbolwith PropertyDescriptor{[[Writable]]:
Algorithms in this section use the conventions described inECMA-262 Algorithm conventions, such as the use of steps and substeps, the use of mathematical operations, and so on. This section may also reference abstract operations and notations defined in other parts of ECMA-262.
When an algorithm says tothrow aSomethingError then this means to construct a new ECMAScriptSomethingError object inthecurrent Realm and to throw it, just as the algorithms in ECMA-262 do.
Note that algorithm steps can call in to other algorithms and abstract operations andnot explicitly handle exceptions that are thrown from them. When an exceptionis thrown by an algorithm or abstract operation and it is not explicitlyhandled by the caller, then it is taken to end the algorithm and propagate outto its caller, and so on.
Consider the following algorithm:
Letx be the ECMAScript value passed in to this algorithm.
Lety be the result of callingToString(x).
Returny.
SinceToString can throw an exception (for example if passed the object({ toString: function() { throw 1 } })), and the exception is not handled in the above algorithm, if one is thrown then it causes this algorithm to end and for the exception to propagate out to its caller, if there is one.
3.1.ECMAScript environment
In an ECMAScript implementation of a given set ofIDL fragments,there will exist a number of ECMAScript objects that correspond todefinitions in thoseIDL fragments.These objects are termed theinitial objects,and comprise the following:
EachRealm must have its own unique set of each oftheinitial objects, createdbefore control enters any ECMAScript execution context associated with theRealm, but after theglobal object for that Realm is created. The [[Prototype]]sof all initial objects in a givenRealm must come fromthat sameRealm.
In an HTML user agent, multipleRealms can exist when multiple frames or windows are created. Each frame or window will have its own set ofinitial objects, which the following HTML document demonstrates:
<!DOCTYPE html> < title > Different Realms</ title > < iframe id = a ></ iframe > < script > var iframe= document. getElementById( "a" ); var w= iframe. contentWindow; // The global object in the frame Object== w. Object; // Evaluates to false, per ECMA-262 Node== w. Node; // Evaluates to false iframeinstanceof w. Node; // Evaluates to false iframeinstanceof w. Object; // Evaluates to false iframe. appendChildinstanceof Function; // Evaluates to true iframe. appendChildinstanceof w. Function; // Evaluates to false </ script >
Note: Allinterfaces define whichRealms they areexposed in.This allows, for example,Realms for Web Workers toexpose different sets of supported interfaces from those exposed in Realmsfor Web pages.
Although at the time of this writing the ECMAScript specification does not reflect this,every ECMAScript object must have anassociatedRealm. The mechanismsfor associating objects with Realms are, for now, underspecified. However, we note thatin the case ofplatform objects, theassociated Realm is equal to the object’srelevant Realm, andfor non-exoticfunction objects (i.e. notcallable proxies, and not bound functions)the associated Realm is equal to the value of thefunction object's [[Realm]] internalslot.
3.2.ECMAScript type mapping
This section describes how types in the IDL map to types in ECMAScript.
Each sub-section below describes how values of a given IDL type are representedin ECMAScript. For each IDL type, it is described how ECMAScript values areconverted to an IDL value when passed to aplatform object expecting that type, and how IDL valuesof that type areconverted to ECMAScript values when returned from a platform object.
Note that the sub-sections and algorithms below also apply toannotated types created by applyingextended attributes to the types named in their headers.
3.2.1.any
Since the IDLany typeis the union of all other IDL types, it can correspond to anyECMAScript value type.
An ECMAScript valueV isconverted to an IDLany value by running the following algorithm:
IfV is
undefined , thenreturn anobjectreference to a special object that representsthe ECMAScriptundefined value.IfV is
null , thenreturn thenull object?reference.IfType(V) is Boolean, thenreturn the
booleanvalue that represents the same truth value.IfType(V) is Number, thenreturn the result ofconvertingV to an
unrestricted double.IfType(V) is String, thenreturn the result ofconvertingV to a
DOMString.IfType(V) is Symbol, thenreturn the result ofconvertingV to a
symbol.IfType(V) is Object, thenreturn an IDL
objectvalue that referencesV.
An IDLany value isconverted to an ECMAScript value as follows. If the value is anobject reference to a special object that represents an ECMAScriptany value as described in the remainder of this section are performed.
3.2.2.void
An ECMAScript valueV isconverted to an IDLvoid value by returning the uniquevoid value, ignoringV.
The unique IDLvoid value isconverted to the ECMAScript
3.2.3.boolean
The IDLboolean valuetrue isconverted to the ECMAScriptboolean valuefalse is converted to the ECMAScript
3.2.4.Integer types
Mathematical operations used in this section,including those defined inECMA-262 Algorithm conventions,are to be understood as computing exact mathematical resultson mathematical real numbers.
In effect, wherex is a Number value,“operating onx” is shorthand for“operating on the mathematical real number that represents the same numeric value asx”.
3.2.4.1.byte
An ECMAScript valueV isconverted to an IDLbyte value by running the following algorithm:
Letx be?ConvertToInt(V, 8, "
signed").Return the IDL
bytevalue that represents the same numeric value asx.
The result ofconverting an IDLbyte value to an ECMAScript value is a Number that represents the same numeric value as the IDLbyte value. The Number value will be an integer in the range [−128, 127].
3.2.4.2.octet
An ECMAScript valueV isconverted to an IDLoctet value by running the following algorithm:
Letx be?ConvertToInt(V, 8, "
unsigned").Return the IDL
octetvalue that represents the same numeric value asx.
The result ofconverting an IDLoctet value to an ECMAScript value is a Number that represents the same numeric value as the IDLoctet value. The Number value will be an integer in the range [0, 255].
3.2.4.3.short
An ECMAScript valueV isconverted to an IDLshort value by running the following algorithm:
Letx be?ConvertToInt(V, 16, "
signed").Return the IDL
shortvalue that represents the same numeric value asx.
The result ofconverting an IDLshort value to an ECMAScript value is a Number that represents the same numeric value as the IDLshort value. The Number value will be an integer in the range [−32768, 32767].
3.2.4.4.unsigned short
An ECMAScript valueV isconverted to an IDLunsigned short value by running the following algorithm:
Letx be?ConvertToInt(V, 16, "
unsigned").Return the IDL
unsigned shortvalue that represents the same numeric value asx.
The result ofconverting an IDLunsigned short value to an ECMAScript value is a Number that represents the same numeric value as the IDLunsigned short value. The Number value will be an integer in the range [0, 65535].
3.2.4.5.long
An ECMAScript valueV isconverted to an IDLlong value by running the following algorithm:
Letx be?ConvertToInt(V, 32, "
signed").Return the IDL
longvalue that represents the same numeric value asx.
The result ofconverting an IDLlong value to an ECMAScript value is a Number that represents the same numeric value as the IDLlong value. The Number value will be an integer in the range [−2147483648, 2147483647].
3.2.4.6.unsigned long
An ECMAScript valueV isconverted to an IDLunsigned long value by running the following algorithm:
Letx be?ConvertToInt(V, 32, "
unsigned").Return the IDL
unsigned longvalue that represents the same numeric value asx.
The result ofconverting an IDLunsigned long value to an ECMAScript value is a Number that represents the same numeric value as the IDLunsigned long value. The Number value will be an integer in the range [0, 4294967295].
3.2.4.7.long long
An ECMAScript valueV isconverted to an IDLlong long value by running the following algorithm:
Letx be?ConvertToInt(V, 64, "
signed").Return the IDL
long longvalue that represents the same numeric value asx.
The result ofconverting an IDLlong long value to an ECMAScript value is a Number value that represents the closest numeric value to thelong long, choosing the numeric value with aneven significand if there are twoequally close values. If thelong long is in the range [−253 + 1, 253 − 1], then the Number will be able to represent exactly the same value as thelong long.
3.2.4.8.unsigned long long
An ECMAScript valueV isconverted to an IDLunsigned long long value by running the following algorithm:
Letx be?ConvertToInt(V, 64, "
unsigned").Return the IDL
unsigned long longvalue that represents the same numeric value asx.
The result ofconverting an IDLunsigned long long value to an ECMAScript value is a Number value that represents the closest numeric value to theunsigned long long, choosing the numeric value with aneven significand if there are twoequally close values. If theunsigned long long is less than or equal to 253 − 1, then the Number will be able to represent exactly the same value as theunsigned long long.
3.2.4.9.Abstract operations
ConvertToInt(V,bitLength,signedness):
IfbitLength is 64, then:
LetupperBound be 253 − 1.
Ifsignedness is "
unsigned", then letlowerBound be 0.Otherwise letlowerBound be −253 + 1.
Note: this ensures
long longtypesassociated with [EnforceRange] or[Clamp]extended attributes are representable in ECMAScript’sNumber type as unambiguous integers.
Otherwise, ifsignedness is "
unsigned", then:LetlowerBound be 0.
LetupperBound be 2bitLength − 1.
Otherwise:
LetlowerBound be -2bitLength − 1.
LetupperBound be 2bitLength − 1 − 1.
Ifx is −0, then setx to +0.
If the conversion is to an IDL typeassociated with the [
EnforceRange]extended attribute, then:Ifx is not
NaN and the conversion is to an IDL typeassociated with the [Clamp] extended attribute,then:Ifx is
NaN , +0, +∞, or −∞,then return +0.Setx to!IntegerPart(x).
Setx toxmodulo 2bitLength.
Ifsignedness is "
signed" andx ≥ 2bitLength − 1,then returnx − 2bitLength.Otherwise, returnx.
3.2.5.float
An ECMAScript valueV isconverted to an IDLfloat value by running the following algorithm:
LetS be the set of finite IEEE 754 single-precision floatingpoint values except −0, but with two special values added: 2128 and−2128.
Lety be the number inS that is closesttox, selecting the number with aneven significand if there are twoequally close values.(The two special values 2128 and −2128 are considered to have even significands for this purpose.)
Ify is +0 andx is negative, return −0.
Returny.
The result ofconverting an IDLfloat value to an ECMAScript value is the Number value that represents the same numeric value as the IDLfloat value.
3.2.6.unrestricted float
An ECMAScript valueV isconverted to an IDLunrestricted float value by running the following algorithm:
Ifx is
NaN , then return the IDLunrestricted floatvalue that represents the IEEE 754 NaN value with the bit pattern 0x7fc00000[IEEE-754].LetS be the set of finite IEEE 754 single-precision floatingpoint values except −0, but with two special values added: 2128 and−2128.
Lety be the number inS that is closesttox, selecting the number with aneven significand if there are twoequally close values.(The two special values 2128 and −2128 are considered to have even significands for this purpose.)
Ify is 2128, return +∞.
Ify is −2128, return −∞.
Ify is +0 andx is negative, return −0.
Returny.
Note: Since there is only a single ECMAScript
The result ofconverting an IDLunrestricted float value to an ECMAScript value is a Number:
If the IDL
unrestricted floatvalue is a NaN,then the Number value isNaN .Otherwise, the Number value isthe one that represents the same numeric value as the IDL
unrestricted floatvalue.
3.2.7.double
The result ofconverting an IDLdouble value to an ECMAScript value is the Number value that represents the same numeric value as the IDLdouble value.
3.2.8.unrestricted double
An ECMAScript valueV isconverted to an IDLunrestricted double value by running the following algorithm:
Ifx is
NaN , thenreturn the IDLunrestricted doublevalue that representsthe IEEE 754 NaN value with the bit pattern 0x7ff8000000000000[IEEE-754].Return the IDL
unrestricted doublevaluethat represents the same numeric value asx.
Note: Since there is only a single ECMAScript
The result ofconverting an IDLunrestricted double value to an ECMAScript value is a Number:
If the IDL
unrestricted doublevalue is a NaN,then the Number value isNaN .Otherwise, the Number value isthe one that represents the same numeric value as the IDL
unrestricted doublevalue.
3.2.9.DOMString
An ECMAScript valueV isconverted to an IDLDOMString value by running the following algorithm:
IfV is
null and the conversion is to an IDL typeassociated with the [TreatNullAs] extendedattribute, then return theDOMStringvalue that represents the empty string.Letx beToString(V).
Return the IDL
DOMStringvalue that represents the same sequence of code units as the one the ECMAScript String valuex represents.
The result ofconverting an IDLDOMString value to an ECMAScript value is the String value that represents the same sequence ofcode units that the IDLDOMString represents.
3.2.10.ByteString
An ECMAScript valueV isconverted to an IDLByteString value by running the following algorithm:
Letx beToString(V).
If the value of anyelement ofx is greater than 255, thenthrow a
TypeError.Return an IDL
ByteStringvaluewhose length is the length ofx, and where the value of each element isthe value of the corresponding element ofx.
The result ofconverting an IDLByteString value to an ECMAScript value is a String value whose length is the length of theByteString, and the value of eachelement of which is the value of the corresponding element of theByteString.
3.2.11.USVString
An ECMAScript valueV isconverted to an IDLUSVString value by running the following algorithm:
Letstring be the result ofconvertingV to a
DOMString.Return an IDL
USVStringvalue that is the result ofconvertingstring to a sequence ofUnicode scalar values.
An IDLUSVString value isconverted to an ECMAScript value by running the following algorithm:
LetscalarValues be the sequence ofUnicode scalar values the
USVStringrepresents.Letstring be the sequence ofcode units that results from encodingscalarValues in UTF-16.
Return the String value that represents the same sequence ofcode units asstring.
3.2.12.object
IDLobject values are represented by ECMAScript Object values.
The result ofconverting an IDLobject value to an ECMAScript value is the Object value that represents a reference to the same object that the IDLobject represents.
3.2.13.symbol
IDLsymbol values are represented by ECMAScript Symbol values.
The result ofconverting an IDLsymbol value to an ECMAScript value is the Symbol value that represents a reference to the same symbol that the IDLsymbol represents.
3.2.14.Interface types
IDLinterface type values are represented by ECMAScript Object values (includingfunction objects).
An ECMAScript valueV isconverted to an IDLinterface type value by running the following algorithm (whereI is theinterface):
IfVimplementsI, then return the IDLinterface type value that represents a reference to that platform object.
The result ofconverting an IDLinterface type value to an ECMAScript value is the Object value that represents a reference to the same object that the IDLinterface type value represents.
3.2.15.Callback interface types
IDLcallback interface type values are represented by ECMAScript Object values (includingfunction objects).
An ECMAScript valueV isconverted to an IDLcallback interface type value by running the following algorithm:
Return the IDLcallback interface type value that represents a reference toV, withtheincumbent settings object as thecallback context.
The result ofconverting an IDLcallback interface type value to an ECMAScript value is the Object value that represents a reference to the same object that the IDLcallback interface type value represents.
3.2.16.Dictionary types
IDLdictionary type values are representedby ECMAScript Object values. Properties onthe object (or its prototype chain) correspond todictionary members.
An ECMAScript valueesDict isconverted to an IDLdictionary type value by running the following algorithm (whereD is thedictionary type):
IfType(esDict) is not Undefined, Null or Object, thenthrow a
TypeError.LetidlDict be an empty dictionary value of typeD;everydictionary member is initially considered to benot present.
Letdictionaries be a list consisting ofD and all ofD’sinherited dictionaries,in order from least to most derived.
For each dictionarydictionary indictionaries, in order:
For each dictionary membermember declared ondictionary, in lexicographical order:
Letkey be theidentifier ofmember.
LetesMemberValue be an ECMAScript value, depending onType(esDict):
IfesMemberValue is not
undefined , then:LetidlMemberValue be the result ofconvertingesMemberValue to an IDL value whose type is the typemember is declared to be of.
Set the dictionary member onidlDict with key namekey to the valueidlMemberValue. This dictionary member is considered to bepresent.
Otherwise, ifesMemberValue is
undefined butmember has adefault value, then:LetidlMemberValue bemember’s default value.
Set the dictionary member onidlDict with key namekey to the valueidlMemberValue. This dictionary member is considered to bepresent.
Otherwise, ifesMemberValue is
undefined andmember is arequired dictionary member, then throw aTypeError.
ReturnidlDict.
Note: The order thatdictionary members are lookedup on the ECMAScript object are not necessarily the same as the object’s property enumeration order.
An IDL dictionary valueV isconverted to an ECMAScript Object value by running the following algorithm (whereD is thedictionary):
LetO be!ObjectCreate(
%ObjectPrototype%).Letdictionaries be a list consisting ofD and all ofD’sinherited dictionaries,in order from least to most derived.
For each dictionarydictionary indictionaries, in order:
For each dictionary membermember declared ondictionary, in lexicographical order:
Letkey be theidentifier ofmember.
If the dictionary member namedkey ispresent inV, then:
LetidlValue be the value ofmember onV.
Letvalue be the result ofconvertingidlValue to an ECMAScript value.
Perform!CreateDataProperty(O,key,value).
ReturnO.
3.2.17.Enumeration types
IDLenumeration types are represented by ECMAScript Stringvalues.
An ECMAScript valueV isconverted to an IDLenumeration type value as follows (whereE is theenumeration):
LetS be the result of callingToString(V).
IfS is not one ofE’senumeration values,thenthrow a
TypeError.Return the enumeration value of typeE that is equal toS.
The result ofconverting an IDLenumeration type value to an ECMAScript value is the String value that represents the same sequence ofcode units as theenumeration value.
3.2.18.Callback function types
IDLcallback function types are represented by ECMAScriptfunction objects, except in the[TreatNonObjectAsNull] case, when they can be any object.
An ECMAScript valueV isconverted to an IDLcallback function type value by running the following algorithm:
If the result of callingIsCallable(V) is
false and the conversion to an IDL valueis not being performed duetoV being assigned to anattribute whose type is anullablecallback function that is annotated with [TreatNonObjectAsNull],thenthrow aTypeError.Return the IDLcallback function type valuethat represents a reference to the same object thatV represents, with theincumbent settings object as thecallback context.
The result ofconverting an IDLcallback function type value to an ECMAScript value is a reference to the same object that the IDLcallback function type value represents.
3.2.19.Nullable types —T?
IDLnullable type values are representedby values of either the ECMAScript type corresponding to theinner IDL type, orthe ECMAScript
An ECMAScript valueV isconverted to an IDLnullable typeT? value (whereT is theinner type) as follows:
IfType(V) is not Object, andthe conversion to an IDL value is being performed duetoV being assigned to anattribute whose type is anullablecallback function that is annotated with [
TreatNonObjectAsNull],then return the IDLnullable typeT?valuenull .Otherwise, ifV is
null orundefined , then return the IDLnullable typeT?valuenull .Otherwise, return the result ofconvertingV using the rules for theinner IDL type
T.
The result ofconverting an IDLnullable type value to an ECMAScript value is:
If the IDLnullable type
T?value isnull ,then the ECMAScript value isnull .Otherwise, the ECMAScript value is the result ofconverting the IDLnullable type valueto theinner IDL type
T.
3.2.20.Sequences — sequence<T>
IDLsequence<T> values are represented byECMAScript Array values.
An ECMAScript valueV isconverted to an IDLsequence<T> value as follows:
Letmethod be?GetMethod(V,
@@iterator).Return the result ofcreating a sequence fromV andmethod.
An IDL sequence valueS of typesequence<T> isconverted to an ECMAScript Array object as follows:
Letn be the length ofS.
LetA be a new Array object created as if by the expression
[].Initializei to be 0.
Whilei <n:
LetV be the value inS at indexi.
LetE be the result ofconvertingV to an ECMAScript value.
LetP be the result of callingToString(i).
CallCreateDataProperty(A,P,E).
Seti toi + 1.
ReturnA.
3.2.20.1.Creating a sequence from an iterable
To create an IDL value of typesequence<T> given an iterableiterable and an iterator gettermethod, perform the following steps:
Letiter be?GetIterator(iterable,
sync ,method).Initializei to be 0.
Repeat
Letnext be?IteratorStep(iter).
Ifnext is
false ,then return an IDL sequence value of typesequence<T> of lengthi, where the value of the elementat indexj isSj.LetnextItem be?IteratorValue(next).
InitializeSi to the result ofconvertingnextItem to an IDL value of typeT.
Seti toi + 1.
The followinginterface defines anattribute of a sequence type as well as anoperation with an argument of a sequence type.
[Exposed =Window ]interface Canvas {sequence <DOMString >getSupportedImageCodecs ();void drawPolygon (sequence <double >coordinates );sequence <double >getLastDrawnPolygon (); // ...};
In an ECMAScript implementation of this interface, an Array object with elements of type String is used to represent asequence<DOMString>, while an Array with elements of type Number represents asequence<double>. The Array objects are effectively passed by value; every time thegetSupportedImageCodecs() function is called a new Array is returned, and whenever an Array is passed todrawPolygon no reference will be kept after the call completes.
// Obtain an instance of Canvas. Assume that getSupportedImageCodecs() // returns a sequence with two DOMString values: "image/png" and "image/svg+xml". var canvas= getCanvas(); // An Array object of length 2. var supportedImageCodecs= canvas. getSupportedImageCodecs(); // Evaluates to "image/png". supportedImageCodecs[ 0 ]; // Each time canvas.getSupportedImageCodecs() is called, it returns a // new Array object. Thus modifying the returned Array will not // affect the value returned from a subsequent call to the function. supportedImageCodecs[ 0 ] = "image/jpeg" ; // Evaluates to "image/png". canvas. getSupportedImageCodecs()[ 0 ]; // This evaluates to false, since a new Array object is returned each call. canvas. getSupportedImageCodecs() == canvas. getSupportedImageCodecs(); // An Array of Numbers... var a= [ 0 , 0 , 100 , 0 , 50 , 62.5 ]; // ...can be passed to a platform object expecting a sequence<double>. canvas. drawPolygon( a); // Each element will be converted to a double by first calling ToNumber(). // So the following call is equivalent to the previous one, except that // "hi" will be alerted before drawPolygon() returns. a= [ false , '' , { valueOf: function () { alert( 'hi' ); return 100 ; } }, 0 , '50' , new Number( 62.5 )]; canvas. drawPolygon( a); // Modifying an Array that was passed to drawPolygon() is guaranteed not to // have an effect on the Canvas, since the Array is effectively passed by value. a[ 4 ] = 20 ; var b= canvas. getLastDrawnPolygon(); alert( b[ 4 ]); // This would alert "50".
3.2.21.Records — record<K,V>
IDLrecord<K,V> values are represented byECMAScript Object values.
An ECMAScript valueO isconverted to an IDLrecord<K,V> value as follows:
Letresult be a new empty instance of
record<K,V>.Letkeys be?O.[[OwnPropertyKeys]]().
For eachkey ofkeys:
Letdesc be?O.[[GetOwnProperty]](key).
Ifdesc is not
undefined anddesc.[[Enumerable]] istrue :LettypedKey bekeyconverted to an IDL value of typeK.
LettypedValue bevalueconverted to an IDL value of typeV.
Setresult[typedKey] totypedValue.
Note: it’s possible thattypedKey is already inresult, ifO is a proxyobject.
Returnresult.
An IDLrecord<…> valueD isconverted to an ECMAScript value as follows:
Letresult be!ObjectCreate(
%ObjectPrototype%).For eachkey →value ofD:
LetesKey bekeyconverted to an ECMAScript value.
LetesValue bevalueconverted to an ECMAScript value.
Letcreated be!CreateDataProperty(result,esKey,esValue).
Assert:created is
true .
Returnresult.
Passing the ECMAScript value{b: 3, a: 4} as arecord<DOMString, double> argument would result in the IDL value «[ "b" → 3, "a" → 4 ]».
Records only considerownenumerable properties, so given an IDL operationrecord<DOMString, double> identity(record<DOMString, double> arg) which returns its argument, the following code passes its assertions:
let proto= { a: 3 , b: 4 }; let obj= { __proto__: proto, d: 5 , c: 6 } Object. defineProperty( obj, "e" , { value: 7 , enumerable: false }); let result= identity( obj); console. assert( result. a=== undefined ); console. assert( result. b=== undefined ); console. assert( result. e=== undefined ); let entries= Object. entries( result); console. assert( entries[ 0 ][ 0 ] === "d" ); console. assert( entries[ 0 ][ 1 ] === 5 ); console. assert( entries[ 1 ][ 0 ] === "c" ); console. assert( entries[ 1 ][ 1 ] === 6 );
Record keys and values can be constrained, although keys can only be constrained among the three string types. The following conversions have the described results:
| Value | Passed to type | Result |
|---|---|---|
{"😞": 1} | record<ByteString, double> | TypeError |
{"\uD83D": 1} | record<USVString, double> | «[ "\uFFFD" → 1 ]» |
{"\uD83D": {hello: "world"}} | record<DOMString, double> | «[ "\uD83D" → 0 ]» |
3.2.22.Promise types — Promise<T>
IDLpromise type values are represented by ECMAScriptPromiseCapability records.
An ECMAScript valueV isconverted to an IDLPromise<T> value as follows:
LetpromiseCapability be?NewPromiseCapability(
%Promise%).ReturnpromiseCapability.
The result ofconverting an IDLpromise type value to an ECMAScript value is the value of the [[Promise]] field of the record that IDLpromise type represents.
3.2.22.1.Creating and manipulating Promises
Tocreate a newPromise<T> in aRealmrealm, perform the following steps:
Letconstructor berealm.[[Intrinsics]].[[
%Promise%]].Return?NewPromiseCapability(constructor).
To create aresolved promise of typePromise<T>, withx (a value of typeT) in aRealmrealm, perform the following steps:
Letvalue be the result ofconvertingx to anECMAScript value.
Letconstructor berealm.[[Intrinsics]].[[
%Promise%]].LetpromiseCapability be?NewPromiseCapability(constructor).
Perform!Call(promiseCapability.[[Resolve]],
undefined ,«value »).ReturnpromiseCapability.
To create arejected promise of typePromise<T>, with reasonr (an ECMAScript value) in aRealmrealm, perform the following steps:
Letconstructor berealm.[[Intrinsics]].[[
%Promise%]].LetpromiseCapability be?NewPromiseCapability(constructor).
ReturnpromiseCapability.
Toresolve aPromise<T>p withx (a value of typeT), perform the following steps:
Ifx is not given, then let it be the
voidvalue.Letvalue be the result ofconvertingx to anECMAScript value.
IfT isvoid, then thex argument is optional, allowing a simpler "resolve p" usage.
Toreject aPromise<T>p with reasonr (an ECMAScript value), perform the following steps:
Toreact to aPromise<T>promise, given one or two sets of steps to perform, covering when the promise is fulfilled, rejected, or both, perform the following steps:
LetonFulfilledSteps be the following steps given argumentV:
Letvalue be the result ofconvertingV to an IDLvalue of typeT.
If there are no steps that are required to be run if the promise was fulfilled, thenreturn
undefined .Letresult be the result of performing any steps that were required to be run ifthe promise was fulfilled, givenvalue ifT is not
void.Returnresult,converted to an ECMAScript value.
LetonFulfilled be!CreateBuiltinFunction(onFulfilledSteps, « »):
LetonRejectedSteps be the following steps given argumentR:
Letreason be the result ofconvertingR to an IDL value of type
any.If there are no steps that are required to be run if the promise was rejected, thenreturn
undefined .Letresult be the result of performing any steps that were required to be run if thepromise was rejected, givenreason.
Returnresult,converted to an ECMAScript value.
LetonRejected be!CreateBuiltinFunction(onRejectedSteps, « »):
Letconstructor bepromise.[[Promise]].[[Realm]].[[Intrinsics]].[[
%Promise%]].LetnewCapability be?NewPromiseCapability(constructor).
Note: Not all callers will use the returned
Promise. Implementations might wish toavoid creatingnewCapability in those cases.Return!PerformPromiseThen(promise.[[Promise]],onFulfilled,onRejected,newCapability).
Note: This algorithm will behave in a very similar way to thePromise.then() method. In particular, if the steps return a value of typeU orPromise<U>, this algorithm returns aPromise<U> as well.
To perform some stepsupon fulfillment of aPromise<T>promise given some stepssteps taking a value of typeT, perform the following steps:
React topromise:
Ifpromise was fulfilled with valuev, then:
Performsteps withv.
To perform some stepsupon rejection of aPromise<T>promise given some stepssteps taking an ECMAScript value, perform the following steps:
React topromise:
Ifpromise was rejected with reasonr, then:
Performsteps withr.
Towait for all with alist ofPromise<T> valuespromises, with success stepssuccessSteps that take alist ofT values and failure stepsfailureSteps that take a rejection reasonany value, perform the following steps:
LetfullfilledCount be 0.
Letrejected be false.
LetrejectionHandlerSteps be the following steps givenarg:
Ifrejected is true, abort these steps.
Setrejected to true.
PerformfailureSteps givenarg.
LetrejectionHandler be!CreateBuiltinFunction(rejectionHandlerSteps, « »):
Lettotal bepromises’ssize.
Iftotal is 0, then:
Queue a microtask to performsuccessSteps given « ».
Return.
Letindex be 0.
Letresult be alist containingtotal null values.
For eachpromise ofpromises:
LetpromiseIndex beindex.
LetfulfillmentHandler be the following steps givenarg:
Setresult[promiseIndex] toarg.
SetfullfilledCount tofullfilledCount + 1.
IffullfilledCount equalstotal, then performsuccessSteps givenresult.
LetfulfillmentHandler be!CreateBuiltinFunction(fulfillmentHandler, « »):
PerformPerformPromiseThen(promise,fulfillmentHandler,rejectionHandler).
Setindex toindex + 1.
Toget a promise for waiting for all with alist ofPromise<T> valuespromises and aRealmrealm, perform the following steps:
Letpromise bea new promise of type
Promise<sequence<T>>inrealm.LetsuccessSteps be the following steps, givenresults:
Resolvepromise withresults.
LetfailureSteps be the following steps, givenreason:
Rejectpromise withreason.
Wait for all withpromises, givensuccessSteps andfailureSteps.
Returnpromise.
This phrase is useful when you wish to aggregate the results of multiple promises, and then produceanother promise from them, in the same way thatPromise.all() functions forJavaScript code.
3.2.22.2.Examples
delay is anoperation that returns a promise that will be fulfilled in a number of milliseconds. It illustrates how simply you can resolve a promise, with one line of prose.
interface I {Promise <void >delay (unrestricted double ms );};
Thedelay(ms) method steps are:
Letrealm bethis’srelevant Realm.
Ifms is NaN, letms be +0; otherwise letms be the maximum ofms and +0.
Letp bea new promise inrealm.
Run the following stepsin parallel:
Waitms milliseconds.
Resolvep.
Returnp.
ThevalidatedDelayoperation is much likethedelay function, except it will validate its arguments. This shows how to use rejected promises to signal immediate failure before even starting any asynchronous operations.
interface I {Promise <void >validatedDelay (unrestricted double ms );};
ThevalidatedDelay(ms) method steps are:
Letrealm bethis’srelevant Realm.
Ifms is NaN, returna promise rejected with a
TypeErrorinrealm.Ifms < 0, returna promise rejected with a
RangeErrorinrealm.Letp bea new promise inrealm.
Run the following stepsin parallel:
Waitms milliseconds.
Resolvep.
Returnp.
addDelay is anoperation that adds an extra number of milliseconds of delay betweenpromise settling and the returned promise settling.
interface I {Promise <any >addDelay (Promise <any >promise ,unrestricted double ms );};
TheaddDelay(ms,promise) method steps are:
Letrealm bethis’srelevant Realm.
LettaskSource be some appropriatetask source.
Ifms is NaN, letms be +0; otherwise letms be the maximum ofms and +0.
Letp bea new promise inrealm.
React topromise:
Ifpromise was fulfilled with valuev, then:
Run the following stepsin parallel:
Waitms milliseconds.
Queue a task to run the following steps ontaskSource:
Resolvep withv.
Ifpromise was rejected with reasonr, then:
Run the following stepsin parallel:
Waitms milliseconds.
Queue a task to run the following steps ontaskSource:
Rejectp withr.
Returnp.
environment.ready is anattribute that signals when some part of some environment, e.g. a DOM document, becomes "ready". It illustrates how to encode environmental asynchronicity.
interface Environment {readonly attribute Promise <void >ready ;};
EveryEnvironment object must have aready promise, which is aPromise<void>.
Theready attribute getter steps are:
Returnthis’sready promise.
To create anEnvironment object in aRealmrealm, perform the following steps:
Letenvironment benew
Environmentobject inrealm.Setenvironment’sready promise toa new promise inrealm.
Run the following stepsin parallel:
Do some asynchronous work.
Ifenvironment becomes ready successfully,resolveenvironment’sready promise.
Ifenvironment fails to become ready,rejectenvironment’sready promise with a "
NetworkError"DOMException.
Returnenvironment.
addBookmark is anoperation that requests that the user add the current web page as a bookmark. It’s drawn fromsome iterative design work and illustrates a more real-world scenario of appealing to environmental asynchrony, as well as immediate rejections.
interface I {Promise <void >addBookmark ();};
TheaddBookmark() method steps are:
If this method was not invoked as a result of explicit user action, returna promise rejected with a "
SecurityError"DOMException.If the document’s mode of operation is standalone, returna promise rejected with a"
NotSupportedError"DOMException.Letpromise bea new promise.
Letinfo be the result of getting a web application’s metadata.
Run the following stepsin parallel:
Usinginfo, and in a manner that is user-agent specific, allow the end user to make achoice as to whether they want to add the bookmark.
If the end-user aborts the request to add the bookmark (e.g., they hit escape, orpress a "cancel" button),rejectpromise with an "
AbortError"DOMException.Otherwise,resolvepromise.
Returnpromise.
Several places in[SERVICE-WORKERS] useget a promise to wait for all.batchRequest illustrates a simplified version of one of their uses. It takes as input asequence of URLs, and returns a promise for asequence ofResponse objects created by fetching the corresponding URL. If any of the fetches fail, it will returna promise rejected with that failure.
interface I {Promise <sequence <Response >>batchRequest (sequence <USVString >urls );};
ThebatchRequest(urls) method steps are:
LetresponsePromises be « ».
For eachurl ofurls:
Letp be the result ofgetting a promise to wait for all withresponsePromises.
Returnp.
3.2.23.Union types
IDLunion type values are represented by ECMAScript valuesthat correspond to the union’smember types.
Toconvert an ECMAScript valueV to an IDLunion type value is done as follows:
If theunion typeincludes a nullable type andV is
null orundefined ,then return the IDL valuenull .Lettypes be theflattened member types of theunion type.
IfV is
null orundefined , then:Iftypes includes adictionary type, then return theresult ofconvertingV to that dictionary type.
IfVis a platform object, then:
Iftypes includes aninterface type thatVimplements, then return the IDL value that is a reference to the objectV.
Iftypes includes
object, then return the IDL valuethat is a reference to the objectV.
IfType(V) is Object andV has an [[ArrayBufferData]]internal slot, then:
Iftypes includes
ArrayBuffer, then return theresult ofconvertingV toArrayBuffer.Iftypes includes
object, then return the IDL valuethat is a reference to the objectV.
IfType(V) is Object andV has a [[DataView]]internal slot, then:
Iftypes includes
DataView, then return theresult ofconvertingV toDataView.Iftypes includes
object, then return the IDL valuethat is a reference to the objectV.
IfType(V) is Object andV has a [[TypedArrayName]]internal slot, then:
Iftypes includes atyped array type whose name is the value ofV’s [[TypedArrayName]]internal slot, then return theresult ofconvertingV to that type.
Iftypes includes
object, then return the IDL valuethat is a reference to the objectV.
IfIsCallable(V) is true, then:
Iftypes includes acallback function type, then return the result ofconvertingV to that callback function type.
Iftypes includes
object, then return the IDL valuethat is a reference to the objectV.
IfType(V) is Object, then:
Iftypes includes asequence type, then
Letmethod be?GetMethod(V,
@@iterator).Ifmethod is not
undefined ,return the result ofcreating a sequence of that type fromV andmethod.
Iftypes includes afrozen array type, then
Letmethod be?GetMethod(V,
@@iterator).Ifmethod is not
undefined ,return the result ofcreating a frozen array of that type fromV andmethod.
Iftypes includes adictionary type, then return theresult ofconvertingV to that dictionary type.
Iftypes includes arecord type, then return theresult ofconvertingV to that record type.
Iftypes includes acallback interface type, then return the result ofconvertingV to thatcallback interface type.
Iftypes includes
object, then return the IDL valuethat is a reference to the objectV.
IfType(V) is Boolean, then:
Iftypes includes a
boolean,then return the result ofconvertingV toboolean.
IfType(V) is Number, then:
Iftypes includes anumeric type,then return the result ofconvertingV to thatnumeric type.
Iftypes includes astring type,then return the result ofconvertingV to that type.
Iftypes includes anumeric type,then return the result ofconvertingV to thatnumeric type.
Iftypes includes a
boolean,then return the result ofconvertingV toboolean.
An IDL union type value isconverted to an ECMAScript value as follows. If the value is anobject reference to a special object that represents an ECMAScript
3.2.24.Buffer source types
Values of the IDLbuffer source types are represented by objects of the corresponding ECMAScript class, with the additional restrictionthat unless the type isassociated with the[AllowShared] extended attribute, they can only be backed by ECMAScriptArrayBuffer objects, and notSharedArrayBuffer objects.
An ECMAScript valueV isconverted to an IDLArrayBuffer value by running the following algorithm:
IfType(V) is not Object,orV does not have an [[ArrayBufferData]]internal slot,thenthrow a
TypeError.If the conversion is not to an IDL typeassociated with the [
AllowShared]extended attribute, andIsSharedArrayBuffer(V) is true, thenthrow aTypeError.Return the IDL
ArrayBuffervalue that is a referenceto the same object asV.
An ECMAScript valueV isconverted to an IDLDataView value by running the following algorithm:
IfType(V) is not Object,orV does not have a [[DataView]]internal slot,thenthrow a
TypeError.If the conversion is not to an IDL typeassociated with the [
AllowShared]extended attribute, andIsSharedArrayBuffer(V.[[ViewedArrayBuffer]]) is true,thenthrow aTypeError.Return the IDL
DataViewvalue that is a referenceto the same object asV.
An ECMAScript valueV isconverted to an IDLInt8Array,Int16Array,Int32Array,Uint8Array,Uint16Array,Uint32Array,Uint8ClampedArray,Float32Array orFloat64Array value by running the following algorithm:
LetT be the IDL typeV is being converted to.
LettypedArrayName be thename ofT’sinner type ifT is anannotated type, or thename ofT otherwise.
IfType(V) is not Object,orV does not have a [[TypedArrayName]]internal slot with a value equal totypedArrayName,thenthrow a
TypeError.If the conversion is not to an IDL typeassociated with the [
AllowShared]extended attribute, andIsSharedArrayBuffer(V.[[ViewedArrayBuffer]]) is true,thenthrow aTypeError.Return the IDL value of typeT that is a reference to the same object asV.
The result ofconverting an IDL value of anybuffer source type to an ECMAScript value is the Object value that representsa reference to the same object that the IDL value represents.
Whengetting a reference to orgetting a copy of the bytes held by a buffer source that is an ECMAScriptArrayBuffer,DataView or typed array object, these steps must be followed:
LetO be the ECMAScript object that is the buffer source.
InitializearrayBuffer toO.
Initializeoffset to 0.
Initializelength to 0.
IfO has a [[ViewedArrayBuffer]]internal slot, then:
SetarrayBuffer to the value ofO’s [[ViewedArrayBuffer]]internal slot.
Setoffset to the value ofO’s [[ByteOffset]]internal slot.
Setlength to the value ofO’s [[ByteLength]]internal slot.
Otherwise, setlength to the value ofO’s [[ArrayBufferByteLength]]internal slot.
IfIsDetachedBuffer(arrayBuffer) is
true , thenreturn the empty byte sequence.Letdata be the value ofO’s [[ArrayBufferData]]internal slot.
Return a reference to or copy of (as required) thelength bytes indata starting at byte offsetoffset.
Todetach anArrayBuffer, these steps must be followed:
LetO be the ECMAScript object that is the
ArrayBuffer.Perform!DetachArrayBuffer(O).
3.2.25.Frozen arrays — FrozenArray<T>
Values of frozen array types are represented by frozen ECMAScriptArray object references.
An ECMAScript valueV isconverted to an IDLFrozenArray<T> value by running the following algorithm:
Letvalues be the result ofconvertingV to IDL typesequence<T>.
Return the result ofcreating a frozen array fromvalues.
Tocreate a frozen array from a sequence of values of typeT, follow these steps:
Letarray be the result ofconverting the sequence of values of typeT to an ECMAScript value.
PerformSetIntegrityLevel(array, "
frozen").Returnarray.
The result ofconverting an IDLFrozenArray<T> value to an ECMAScriptvalue is the Object value that represents a referenceto the same object that the IDLFrozenArray<T> represents.
3.2.25.1.Creating a frozen array from an iterable
To create an IDL value of typeFrozenArray<T> given an iterableiterable and an iterator gettermethod, perform the following steps:
Letvalues be the result ofcreating a sequence of typesequence<T> fromiterable andmethod.
Return the result ofcreating a frozen array fromvalues.
3.3.ECMAScript-specific extended attributes
This section defines a number ofextended attributes whose presence affects only the ECMAScript binding.
3.3.1.[AllowShared]
If the [AllowShared]extended attribute appears on one of thebuffer source types, itcreates a new IDL type that allows the buffer source type to be backed by an ECMAScriptSharedArrayBuffer, instead of only by a non-sharedArrayBuffer.
The [AllowShared] extended attribute musttake no arguments.
A type that is not abuffer source type must not beassociated with the [AllowShared] extended attribute.
See the rules for converting ECMAScript values to IDLbuffer source types in§ 3.2.24 Buffer source types for the specific requirements that the use of [AllowShared] entails.
AllowShared] extended attribute, while the other does not:[Exposed =Window ]interface RenderingContext {void readPixels (long width ,long height ,BufferSource pixels );void readPixelsShared (long width ,long height , [AllowShared ]BufferSource pixels );};
With this definition, a call toreadPixels with anSharedArrayBuffer instance, or any typed array orDataView backed by one, will throw aTypeError exception. In contrast, a call toreadPixelsShared will allow such objects as input.
3.3.2.[Clamp]
If the [Clamp]extended attribute appears on one of theinteger types, it creates a newIDL type such that that when an ECMAScript Number is converted to the IDL type,out-of-range values will be clamped to the range of valid values, rather than using the operatorsthat use a modulo operation (ToInt32,ToUint32, etc.).
The [Clamp]extended attribute musttake no arguments.
A type annotated with the [Clamp] extended attribute must not appear in aread only attribute. A type must not beassociated with both the[Clamp] and [EnforceRange] extended attributes. A type that is not aninteger type mustnot beassociated with the [Clamp] extended attribute.
See the rules for converting ECMAScript values to the various IDL integertypes in§ 3.2.4 Integer types for the specific requirements that the use of[Clamp] entails.
In the followingIDL fragment, twooperations are declared that take threeoctet arguments; one uses the [Clamp]extended attribute on all three arguments, while the other does not:
[Exposed =Window ]interface GraphicsContext {void setColor (octet red ,octet green ,octet blue );void setColorClamped ([Clamp ]octet red , [Clamp ]octet green , [Clamp ]octet blue );};
A call tosetColorClamped with Number values that are out of range for anoctet are clamped to the range [0, 255].
// Get an instance of GraphicsContext. var context= getGraphicsContext(); // Calling the non-[Clamp] version uses ToUint8 to coerce the Numbers to octets. // This is equivalent to calling setColor(255, 255, 1). context. setColor( - 1 , 255 , 257 ); // Call setColorClamped with some out of range values. // This is equivalent to calling setColorClamped(0, 255, 255). context. setColorClamped( - 1 , 255 , 257 );
3.3.3.[Default]
If the [Default]extended attribute appears on aregular operation,then it indicates that steps described in thecorresponding default operation must be carried out when the operation is invoked.
The [Default] extended attribute musttake no arguments.
The [Default] extended attribute must notbe used on anything other than aregular operation for which acorresponding default operation has been defined.
As an example, the [Default] extended attribute is suitable for use ontoJSONregular operations:
[Exposed =Window ]interface Animal {attribute DOMString name ;attribute unsigned short age ; [Default ]object toJSON ();};[Exposed =Window ]interface Human :Animal {attribute Dog ?pet ; [Default ]object toJSON ();};[Exposed =Window ]interface Dog :Animal {attribute DOMString ?breed ;};
In the ECMAScript language binding, there would exist atoJSON() method onAnimal,Human, and (via inheritance)Dog objects:
// Get an instance of Human. var alice= getHuman(); // Evaluates to an object like this (notice how "pet" still holds // an instance of Dog at this point): // // { // name: "Alice", // age: 59, // pet: Dog // } alice. toJSON(); // Evaluates to an object like this (notice how "breed" is absent, // as the Dog interface doesn’t declare a default toJSON operation): // // { // name: "Tramp", // age: 6 // } alice. pet. toJSON(); // Evaluates to a string like this: // '{"name":"Alice","age":59,"pet":{"name":"Tramp","age":6}}' JSON. stringify( alice);
3.3.4.[EnforceRange]
If the [EnforceRange]extended attribute appears on one of theinteger types, it createsa new IDL type such that that when an ECMAScript Number is converted to the IDLtype, out-of-range values will cause an exception to be thrown, rather than being converted to avalid value using using the operators that use a modulo operation (ToInt32,ToUint32, etc.).The Number will be rounded toward zero before being checked against its range.
The [EnforceRange]extended attribute musttake no arguments.
A type annotated with the [EnforceRange] extended attribute must not appear in aread only attribute. A type must not beassociated with both the [Clamp] and [EnforceRange] extended attributes. A type that is not aninteger type must not beassociated with the[EnforceRange] extended attribute.
See the rules for converting ECMAScript values to the various IDL integertypes in§ 3.2 ECMAScript type mapping for the specific requirements that the use of[EnforceRange] entails.
In the followingIDL fragment, twooperations are declared that take threeoctet arguments; one uses the [EnforceRange]extended attribute on all three arguments, while the other does not:
[Exposed =Window ]interface GraphicsContext {void setColor (octet red ,octet green ,octet blue );void setColorEnforcedRange ([EnforceRange ]octet red , [EnforceRange ]octet green , [EnforceRange ]octet blue );};
In an ECMAScript implementation of the IDL, a call to setColorEnforcedRange with Number values that are out of range for anoctet will result in an exception being thrown.
// Get an instance of GraphicsContext. var context= getGraphicsContext(); // Calling the non-[EnforceRange] version uses ToUint8 to coerce the Numbers to octets. // This is equivalent to calling setColor(255, 255, 1). context. setColor( - 1 , 255 , 257 ); // When setColorEnforcedRange is called, Numbers are rounded towards zero. // This is equivalent to calling setColor(0, 255, 255). context. setColorEnforcedRange( - 0.9 , 255 , 255.2 ); // The following will cause a TypeError to be thrown, since even after // rounding the first and third argument values are out of range. context. setColorEnforcedRange( - 1 , 255 , 256 );
3.3.5.[Exposed]
When the [Exposed]extended attribute appears onaninterface,partial interface,interface mixin,partial interface mixin,callback interface,namespace,partial namespace, oran individualinterface member,interface mixin member, ornamespace member,it indicates that the construct is exposedon that particular set of global interfaces.
The [Exposed]extended attribute must eithertake an identifier ortake an identifier list.Each of the identifiers mentioned must be aglobal name and be unique.This list of identifiers is known as the construct’sown exposure set.
To get theexposure set of a constructC, run the following steps:
Assert:C is aninterface,callback interface,namespace,interface member,interface mixin member, ornamespace member.
LetH beC’shost interface ifC is aninterface mixin member, or null otherwise.
IfC is aninterface member,interface mixin member, ornamespace member, then:
If the [
Exposed]extended attribute is specified onC, then:IfH is set, return theintersection ofC’sown exposure set andH’sexposure set.
Otherwise, returnC’sown exposure set.
Otherwise, setC to be theinterface,partial interface,interface mixin,partial interface mixin,namespace, orpartial namespaceC is declared on.
IfC is apartial interface,partial interface mixin, orpartial namespace, then:
If the [
Exposed]extended attribute is specified onC, then:IfH is set, return theintersection ofC’sown exposure set andH’sexposure set.
Otherwise, returnC’sown exposure set.
Otherwise, setC to be the originalinterface,interface mixin, ornamespace definition ofC.
IfC is aninterface mixin, then:
If the [
Exposed]extended attribute is specified onC,then return theintersection ofC’sown exposure set andH’sexposure set.Otherwise, setC toH.
Assert:C is aninterface,callback interface ornamespace.
Assert: The [
Exposed]extended attribute is specified onC.ReturnC’sown exposure set.
If [Exposed] appears on anoverloadedoperation,then it must appear identically on all overloads.
The [Exposed] extended attribute must not be specified both onaninterface member,interface mixin member, ornamespace member, and onthepartial interface,partial interface mixin, orpartial namespace definitionthemember is declared on.
Note: This is because adding an [Exposed]extended attribute on apartial interface,partial interface mixin, orpartial namespace is shorthand for annotating each of itsmembers.
If [Exposed] appears on apartial interface orpartial namespace,then the partial’sown exposure set must be a subset oftheexposure set of the partial’s originalinterface ornamespace.
If [Exposed] appears on aninterface ornamespace member,then themember'sexposure set must be a subsetof theexposure set of theinterface ornamespace it is a member of.
If [Exposed] appears both on apartial interface mixin and its originalinterface mixin,then thepartial interface mixin'sown exposure set must be a subset of theinterface mixin'sown exposure set.
If [Exposed] appears both on aninterface mixin member and theinterface mixin it is a member of,then theinterface mixin members'sown exposure set must be a subset of theinterface mixin'sown exposure set.
If an interfaceXinherits from another interfaceY then theexposure set ofX must be a subset of theexposure set ofY.
Note: As aninterface mixin can beincluded by differentinterfaces,theexposure set of itsmembers is a function oftheinterface thatincludes them.If theinterface mixin member,partial interface mixin, orinterface mixin is annotated with an [Exposed]extended attribute,then theinterface mixin member'sexposure set is theintersection of the relevant construct’sown exposure set with the thehost interface'sexposure set.Otherwise, it is thehost interface'sexposure set.
Ifrealm.[[GlobalObject]] does not implement aninterface that is inconstruct’sexposure set, then return false.
Ifconstruct isavailable in both secure and non-secure contexts,then return true.
If therelevant settings object ofrealm.[[GlobalObject]] is asecure context,then return true.
Otherwise, return false.
Note: Since it is not possible for therelevant settings object for an ECMAScript global object to change whether it is asecure context or not over time, an implementation’sdecision to create properties for an interface or interface membercan be made once, at the time theinitial objects are created.
See§ 3.6 Interfaces,§ 3.6.5 Constants,§ 3.6.6 Attributes,§ 3.6.7 Operations, and§ 3.6.8 Common iterator behavior for the specific requirements that the use of[Exposed] entails.
[Exposed] is intended to be used to control whetherinterfaces,callback interfaces,namespaces, or individualinterface,mixin ornamespace members are available for use in workers,Worklet,Window, or any combination of the above.
The following IDL fragment shows how that might be achieved:
[Exposed =Window ,Global =Window ]interface Window { // ...};// By using the same identifier Worker for both SharedWorkerGlobalScope// and DedicatedWorkerGlobalScope, both can be addressed in an [Exposed]// extended attribute at once.[Exposed =Worker ,Global =Worker ]interface SharedWorkerGlobalScope :WorkerGlobalScope { // ...};[Exposed =Worker ,Global =Worker ]interface DedicatedWorkerGlobalScope :WorkerGlobalScope { // ...};// Dimensions is available for use in workers and on the main thread.[Exposed =(Window ,Worker )]interface Dimensions {constructor (double width ,double height );readonly attribute double width ;readonly attribute double height ;};// WorkerNavigator is only available in workers. Evaluating WorkerNavigator// in the global scope of a worker would give you its interface object, while// doing so on the main thread will give you a ReferenceError.[Exposed =Worker ]interface WorkerNavigator { // ...};// Node is only available on the main thread. Evaluating Node// in the global scope of a worker would give you a ReferenceError.[Exposed =Window ]interface Node { // ...};// MathUtils is available for use in workers and on the main thread.[Exposed =(Window ,Worker )]namespace MathUtils {double someComplicatedFunction (double x ,double y );};// WorkerUtils is only available in workers. Evaluating WorkerUtils// in the global scope of a worker would give you its namespace object, while// doing so on the main thread will give you a ReferenceError.[Exposed =Worker ]namespace WorkerUtils {void setPriority (double x );};// NodeUtils is only available in the main thread. Evaluating NodeUtils// in the global scope of a worker would give you a ReferenceError.[Exposed =Window ]namespace NodeUtils {DOMString getAllText (Node node );};
3.3.6.[Global]
If the [Global]extended attribute appears on aninterface,it indicates that objects implementing this interface canbe used as the global object in aRealm,and that the structure of the prototype chain and howproperties corresponding tointerface members will be reflected on the prototype objects will be different from otherinterfaces. Specifically:
Anynamed properties will be exposed on an object in the prototype chain – thenamed properties object –rather than on the object itself.
Interface members from theinterface will correspond to properties on the object itself rather than oninterface prototype objects.
Placing named properties on an object in the prototype chain is done so that variable declarations and bareword assignments will shadow the named property with a property on the global object itself.
Placing properties corresponding to interface members on the object itself will mean that common feature detection methods like the following will work:
var indexedDB= window. indexedDB|| window. webkitIndexedDB|| window. mozIndexedDB|| window. msIndexedDB; var requestAnimationFrame= window. requestAnimationFrame|| window. mozRequestAnimationFrame|| ...;
Because of the way variable declarations are handled in ECMAScript, the code above would result in thewindow.indexedDB andwindow.requestAnimationFrame evaluating to
If the [Global]extended attributes isused on aninterface, then:
The interface must not define anamed property setter.
The interface must not defineindexed property getters orsetters.
The interface must not define aconstructor operation.
The interface must not also be declared with the [
OverrideBuiltins]extended attribute.The interface must notinherit from another interface with the[
OverrideBuiltins] extended attribute.Any other interface must notinherit from it.
If [Global] is specified onapartial interface definition, then that partial interface definition mustbe the part of the interface definition that definesthenamed property getter.
The [Global]extended attribute must notbe used on aninterface that can have morethan one object implementing it in the sameRealm.
Note: This is because thenamed properties object,which exposes the named properties, is in the prototype chain, and it would not makesense for more than one object’s named properties to be exposed on an object thatall of those objects inherit from.
If an interface is declared with the [Global]extended attribute, thenthere must not be more than onemember acrossthe interfacewith the sameidentifier.There also must not be more thanonestringifier or more than oneiterable declaration,asynchronously iterable declaration,maplike declaration orsetlike declaration across those interfaces.
Note: This is because all of themembers of the interfaceget flattened down on to the object thatimplements the interface.
The [Global] extended attributecan also be used to give a name to one or more global interfaces,which can then be referenced by the [Exposed]extended attribute.
The [Global] extended attribute must eithertake an identifier ortake an identifier list.
The identifier argument or identifier list argument the [Global]extended attribute is declared withdefine the interface’sglobal names.
Note: The identifier argument list exists so that more than one global interface canbe addressed with a single name in an [Exposed]extended attribute.
See§ 3.6.4 Named properties object for the specific requirementsthat the use of [Global] entails fornamed properties,and§ 3.6.5 Constants,§ 3.6.6 Attributes and§ 3.6.7 Operations for the requirements relating to the location of propertiescorresponding tointerface members.
TheWindow interface exposes frames as properties on theWindow object. Since theWindow object also serves as the ECMAScript global object, variable declarations or assignments to the named properties will result in them being replaced by the new value. Variable declarations for attributes will not create a property that replaces the existing one.
[Exposed =Window ,Global ]interface Window {getter any (DOMString name );attribute DOMString name ; // ...};
The following HTML document illustrates how the named properties on theWindow object can be shadowed, and how the property for an attribute will not be replaced when declaring a variable of the same name:
<!DOCTYPE html> < title > Variable declarations and assignments on Window</ title > < iframe name = abc ></ iframe > <!-- Shadowing named properties --> < script > window. abc; // Evaluates to the iframe’s Window object. abc= 1 ; // Shadows the named property. window. abc; // Evaluates to 1. </ script > <!-- Preserving properties for IDL attributes --> < script > Window. prototype. def= 2 ; // Places a property on the prototype. window. hasOwnProperty( "length" ); // Evaluates to true. length; // Evaluates to 1. def; // Evaluates to 2. </ script > < script > var length; // Variable declaration leaves existing property. length; // Evaluates to 1. var def; // Variable declaration creates shadowing property. def; // Evaluates to undefined. </ script >
3.3.7.[LegacyNamespace]
The [LegacyNamespace]extended attribute is an undesirable feature. It exists only so that legacy Web platform features can be specified. It should not be used in specifications unless required to specify the behavior of legacy APIs, or for consistency with these APIs. Instead, interface names can be formed with a naming convention of starting with a particular prefix for a set of interfaces, as part of the identifier, rather than using a namespace. Editors who wish to use this feature are strongly advised to discuss this byfiling an issue before proceeding.
If the [LegacyNamespace]extended attribute appears on aninterface, it indicates thattheinterface object for this interface will not be created as a property of the globalobject, but rather as a property of thenamespace identified by the argument to the extendedattribute.
The [LegacyNamespace] extended attributetake an identifier.This identifier must be the identifier of a namespace.
The [LegacyNamespace] and [NoInterfaceObject]extended attributes must not be specified on the same interface.
See§ 3.11.1 Namespace object for details on how an interface is exposed on a namespace.
LegacyNamespace] to be defined inside of it.namespace Foo { };[LegacyNamespace =Foo ]interface Bar {constructor ();};
In an ECMAScript implementation of the above namespace and interface, the constructor Bar can be accessed as follows:
var instance= new Foo. Bar();
3.3.8.[LegacyUnenumerableNamedProperties]
The [LegacyUnenumerableNamedProperties]extended attribute is an undesirable feature. It exists only so that legacy Web platform features can be specified. It should not be used in specifications unless required to specify the behavior of legacy APIs, or for consistency with these APIs. Editors who wish to use this feature are strongly advised to discuss this byfiling an issue before proceeding.
The [LegacyUnenumerableNamedProperties]extended attribute appears on the followinginterfaces:HTMLCollection,NamedNodeMap,HTMLAllCollection,HTMLFormElement,PluginArray,MimeTypeArray,Plugin, andWindow.[DOM][HTML]
If the [LegacyUnenumerableNamedProperties]extended attribute appears on ainterface thatsupports named properties,it indicates that all the interface’s named properties are unenumerable.
The [LegacyUnenumerableNamedProperties]extended attribute musttake no arguments and must not appear on an interfacethat does not define anamed property getter.
If the [LegacyUnenumerableNamedProperties]extended attribute is specified on an interface, then it applies to all its derived interfaces andmust not be specified on any of them.
See§ 3.8.1 [[GetOwnProperty]] for the specific requirements that the use of[LegacyUnenumerableNamedProperties]entails.
3.3.9.[LegacyWindowAlias]
The [LegacyWindowAlias]extended attribute is an undesirable feature. It exists only so that legacy Web platform features can be specified. It should not be used in specifications unless required to specify the behavior of legacy APIs, or for consistency with these APIs. Editors who wish to use this feature are strongly advised to discuss this byfiling an issue before proceeding.
The [LegacyWindowAlias]extended attribute appears on the followinginterfaces:DOMPoint,DOMRect,DOMMatrix, andURL.[GEOMETRY][URL]
If the [LegacyWindowAlias]extended attribute appears on aninterface,it indicates that theWindowinterface will have a propertyfor eachidentifier mentioned in the extended attribute,whose value is theinterface object for the interface.
The [LegacyWindowAlias] extended attribute must eithertake an identifier ortake an identifier list.TheLegacyWindowAlias]'sidentifiers.
Each of theidentifiers of [LegacyWindowAlias]must not be the same as one used by a [LegacyWindowAlias]extended attribute on this interface or another interface,must not be the same as theidentifier used by a [NamedConstructor]extended attribute on this interface or another interface,must not be the same as anidentifier of an interface that has aninterface object,and must not be one of thereserved identifiers.
The [LegacyWindowAlias] and [NoInterfaceObject]extended attributes must not be specified on the same interface.
The [LegacyWindowAlias] and [LegacyNamespace]extended attributes must not be specified on the same interface.
The [LegacyWindowAlias] extended attribute must not be specifiedon an interface that does not include theWindowinterface in itsexposure set.
An interface must not have more than one [LegacyWindowAlias] extended attributes specified.
See§ 3.6 Interfaces for details on how legacy window aliasesare to be implemented.
The following IDL defines an interface that uses the [LegacyWindowAlias] extended attribute.
[Exposed =Window ,LegacyWindowAlias =WebKitCSSMatrix ]interface DOMMatrix :DOMMatrixReadOnly { // ...};
An ECMAScript implementation that supports this interface will expose two properties on theWindow object with the same value and the same characteristics; one for exposing theinterface object normally, and one for exposing it with a legacy name.
WebKitCSSMatrix=== DOMMatrix; // Evaluates to true. var m= new WebKitCSSMatrix(); // Creates a new object that // implements DOMMatrix. m. constructor=== DOMMatrix; // Evaluates to true. m. constructor=== WebKitCSSMatrix; // Evaluates to true. {}. toString. call( m); // Evaluates to '[object DOMMatrix]'.
3.3.10.[LenientSetter]
Specifications should not use [LenientSetter] unless required for compatibility reasons. Pages have been observed where authors have attempted to polyfill an IDL attribute by assigning to the property, but have accidentally done so even if the property exists. In strict mode, this would cause an exception to be thrown, potentially breaking page. Without [LenientSetter], this could prevent a browser from shipping the feature. Editors who wish to use this feature are strongly advised to discuss this byfiling an issue before proceeding.
The [LenientSetter]extended attribute appears on thefullscreenEnabled andfullscreenEnabledattributes of theDocument interface, and on thefullscreenElementattribute of theDocumentOrShadowRootinterface mixin.[FULLSCREEN]
If the [LenientSetter]extended attribute appears on aread onlyregular attribute,it indicates that a no-op setter will be generated for the attribute’saccessor property. This results in erroneous assignments to the propertyin strict mode to be ignored rather than causing an exception to be thrown.
The [LenientSetter] extended attributemusttake no arguments.It must not be used on anything other thanaread onlyregular attribute.
An attribute with the [LenientSetter]extended attribute must not also be declaredwith the [PutForwards]or [Replaceable] extended attributes.
The [LenientSetter] extended attribute must not be used on an attribute declared on anamespace.
See theAttributes section for how[LenientSetter] is to be implemented.
The following IDL fragment defines an interface that uses the [LenientSetter] extended attribute.
[Exposed =Window ]interface Example { [LenientSetter ]readonly attribute DOMString x ;readonly attribute DOMString y ;};
An ECMAScript implementation that supports this interface will have a setter on the accessor property that correspond to x, which allows any assignment to be ignored in strict mode.
"use strict" ; var example= getExample(); // Get an instance of Example. // Fine; while we are in strict mode, there is a setter that is a no-op. example. x= 1 ; // Throws a TypeError, since we are in strict mode and there is no setter. example. y= 1 ;
3.3.11.[LenientThis]
Specifications should not use [LenientThis] unless required for compatibility reasons. Editors who wish to use this feature are strongly advised to discuss this byfiling an issue before proceeding.
The [LenientThis]extended attribute appears on theonreadystatechange,onmouseenter, andonmouseleaveattributes of theDocument interface.[HTML]
If the [LenientThis]extended attribute appears on aregular attribute,it indicates that invocations of the attribute’s getter or setterwith a
The [LenientThis] extended attributemusttake no arguments.It must not be used on astatic attribute.
The [LenientThis] extended attribute must not be used on an attribute declared on anamespace.
See theAttributes section for how[LenientThis]is to be implemented.
The following IDL fragment defines an interface that uses the [LenientThis] extended attribute.
[Exposed =Window ]interface Example { [LenientThis ]attribute DOMString x ;attribute DOMString y ;};
An ECMAScript implementation that supports this interface will allow the getter and setter of the accessor property that corresponds to x to be invoked with something other than anExample object.
var example= getExample(); // Get an instance of Example. var obj= { }; // Fine. example. x; // Ignored, since the this value is not an Example object and [LenientThis] is used. Object. getOwnPropertyDescriptor( Example. prototype, "x" ). get. call( obj); // Also ignored, since Example.prototype is not an Example object and [LenientThis] is used. Example. prototype. x; // Throws a TypeError, since Example.prototype is not an Example object. Example. prototype. y;
3.3.12.[NamedConstructor]
[NamedConstructor]extended attribute is an undesirable feature. It exists only so that legacy Web platform features can be specified. It should not be used in specifications unless required to specify the behavior of legacy APIs, or for consistency with these APIs. Editors who wish to use this feature are strongly advised to discuss this byfiling an issue before proceeding.
The [NamedConstructor]extended attribute appears on the followinginterfaces:HTMLAudioElement,HTMLOptionElement, andHTMLImageElement.[HTML]
If the [NamedConstructor]extended attribute appears on aninterface,it indicates that the ECMAScript global object will have a property with thespecified name whose value is aconstructor that cancreate objects that implement the interface.Multiple [NamedConstructor] extendedattributes may appear on a given interface.
The [NamedConstructor] extended attribute must eithertake an identifier ortake a named argument list.TheNamedConstructor]'sidentifier.The first form,[NamedConstructor=,has the same meaning as using an empty argument list,[NamedConstructor=.For each [NamedConstructor] extended attribute on the interface,there will be a way to construct an object thatimplements the interface by passing the specified arguments to theconstructor that is the value of the aforementioned property.
Theidentifier used for the named constructor must notbe the same as that used by a [NamedConstructor]extended attribute on another interface, must notbe the same as anidentifier used by a [LegacyWindowAlias]extended attribute on this interface or another interface,must not be the same as anidentifier of an interfacethat has aninterface object,and must not be one of thereserved identifiers.
The [NamedConstructor] and [Global]extended attributes must not be specified on thesameinterface.
See§ 3.6.2 Named constructors for details on how named constructorsare to be implemented.
The following IDL defines an interface that uses the [NamedConstructor] extended attribute.
[Exposed =Window ,NamedConstructor =Audio ,NamedConstructor =Audio (DOMString src )]interface HTMLAudioElement :HTMLMediaElement { // ...};
An ECMAScript implementation that supports this interface will allow the construction ofHTMLAudioElement objects using theAudioconstructor.
typeof Audio; // Evaluates to 'function'. var a1= new Audio(); // Creates a new object that implements // HTMLAudioElement, using the zero-argument // constructor. var a2= new Audio( 'a.flac' ); // Creates an HTMLAudioElement using the // one-argument constructor.
3.3.13.[NewObject]
If the [NewObject]extended attribute appears on aregular orstaticoperation,then it indicates that when calling the operation,a reference to a newly created objectmust always be returned.
The [NewObject]extended attribute musttake no arguments.
The [NewObject]extended attribute must notbe used on anything other than aregular orstaticoperation whosereturn type is aninterface type orapromise type.
As an example, this extended attribute is suitable for use on thecreateElement() operation on theDocument interface, since a new object should always be returned when it is called.[DOM]
[Exposed =Window ]interface Document :Node { [NewObject ]Element createElement (DOMString localName ); // ...};
3.3.14.[NoInterfaceObject]
The [NoInterfaceObject]extended attribute is an undesirable feature. It exists only so that legacy Web platform features can be specified. It should not be used in specifications unless required to specify the behavior of legacy APIs, or for consistency with these APIs. Editors who wish to use this feature are strongly advised to discuss this byfiling an issue before proceeding.
The [NoInterfaceObject]extended attribute appears on the followinginterfaces:
Geolocation,Coordinates,Position,PositionError,DeviceAcceleration,DeviceRotationRate,ConstrainablePattern,WEBGL_compressed_texture_astc,WEBGL_compressed_texture_s3tc_srgb,WEBGL_draw_buffers,WEBGL_lose_context,ANGLE_instanced_arrays,EXT_blend_minmax,EXT_color_buffer_float,EXT_disjoint_timer_query,OES_standard_derivatives, andOES_vertex_array_object.[GEOLOCATION-API][ORIENTATION-EVENT][MEDIACAPTURE-STREAMS] (various[WEBGL] extension specifications)
Note: Previously, the [NoInterfaceObject]extended attribute could also be used to annotateinterfaces, which otherinterfaces could then implement (using the defunct "implements statement") as if they were mixins. There is now dedicated syntax to cater for this use case in the form ofinterface mixins andincludes statements. Using the [NoInterfaceObject]extended attribute for this purpose is no longer supported. Specifications which still do are strongly encouraged to migrate tointerface mixins as soon as possible.
If the [NoInterfaceObject]extended attribute appears on aninterface,it indicates that aninterface object will not exist for the interface in the ECMAScript binding.
The [NoInterfaceObject] extended attributemusttake no arguments.
The [NoInterfaceObject] extended attributemust not be specified on an interface that has anyconstructors orstatic operations defined on it.
Note: Combining the [NoInterfaceObject] and [NamedConstructor] extended attribute is notforbidden, however.
An interface that does not have the [NoInterfaceObject] extendedattribute specified must not inheritfrom an interface that has the [NoInterfaceObject] extendedattribute specified.
See§ 3.6 Interfaces for the specific requirements that the use of[NoInterfaceObject] entails.
The followingIDL fragment defines two interfaces, one whose interface object is exposed on the ECMAScript global object, and one whose isn’t:
[Exposed =Window ]interface Storage {void addEntry (unsigned long key ,any value );};[Exposed =Window ,NoInterfaceObject ]interface Query {any lookupEntry (unsigned long key );};
An ECMAScript implementation of the above IDL would allow manipulation ofStorage’s prototype, but notQuery’s.
typeof Storage; // evaluates to "object" // Add some tracing alert() call to Storage.addEntry. var fn= Storage. prototype. addEntry; Storage. prototype. addEntry= function ( key, value) { alert( 'Calling addEntry()' ); return fn. call( this , key, value); }; typeof Query; // evaluates to "undefined" var fn= Query. prototype. lookupEntry; // exception, Query isn’t defined
3.3.15.[OverrideBuiltins]
The [OverrideBuiltins]extended attribute is an undesirable feature. It exists only so that legacy Web platform features can be specified. It should not be used in specifications unless required to specify the behavior of legacy APIs, or for consistency with these APIs. Editors who wish to use this feature are strongly advised to discuss this byfiling an issue before proceeding.
The [OverrideBuiltins]extended attribute appears on theDOMStringMap,Document, andHTMLFormElementinterfaces.[HTML]
If the [OverrideBuiltins]extended attribute appears on aninterface,it indicates that for alegacy platform object implementing the interface,properties corresponding to all ofthe object’ssupported property names will appear to be on the object,regardless of what other properties exist on the object or itsprototype chain. This means that named properties will always shadowany properties that would otherwise appear on the object.This is in contrast to the usual behavior, which is for named propertiesto be exposed only if there is no property with thesame name on the object itself or somewhere on its prototype chain.
The [OverrideBuiltins]extended attribute musttake no arguments and must not appear on an interfacethat does not define anamed property getter or that also is declared with the [Global]extended attribute.If the extended attribute is specified onapartial interface definition, then that partial interface definition mustbe the part of the interface definition that definesthenamed property getter.
If the [OverrideBuiltins] extended attribute is specified on apartial interface definition, it is considered to appear on theinterface itself.
See§ 3.8 Legacy platform objects and§ 3.8.3 [[DefineOwnProperty]] for the specific requirements that the use of[OverrideBuiltins] entails.
The followingIDL fragment defines twointerfaces, one that has anamed property getter and one that does not.
[Exposed =Window ]interface StringMap {readonly attribute unsigned long length ;getter DOMString lookup (DOMString key );};[Exposed =Window ,OverrideBuiltins ]interface StringMap2 {readonly attribute unsigned long length ;getter DOMString lookup (DOMString key );};
In an ECMAScript implementation of these two interfaces, getting certain properties on objects implementing the interfaces will result in different values:
// Obtain an instance of StringMap. Assume that it has "abc", "length" and // "toString" as supported property names. var map1= getStringMap(); // This invokes the named property getter. map1. abc; // This fetches the "length" property on the object that corresponds to the // length attribute. map1. length; // This fetches the "toString" property from the object’s prototype chain. map1. toString; // Obtain an instance of StringMap2. Assume that it also has "abc", "length" // and "toString" as supported property names. var map2= getStringMap2(); // This invokes the named property getter. map2. abc; // This also invokes the named property getter, despite the fact that the "length" // property on the object corresponds to the length attribute. map2. length; // This too invokes the named property getter, despite the fact that "toString" is // a property in map2’s prototype chain. map2. toString;
3.3.16.[PutForwards]
If the [PutForwards]extended attribute appears on aread onlyregular attribute declaration whose type isaninterface type,it indicates that assigning to the attribute will have specific behavior.Namely, the assignment is “forwarded” to the attribute (specified bythe extended attribute argument) on the object that is currentlyreferenced by the attribute being assigned to.
The [PutForwards] extendedattribute musttake an identifier.Assuming that:
A is theattribute on which the [
PutForwards]extended attribute appears,I is theinterface on whichA is declared,
J is theinterface type thatA is declared to be of, and
N is theidentifier argument of the extended attribute,
then there must be anotherattributeB declared onJ whoseidentifier isN. Assignment of a value to the attributeA on an object implementingI will result in that valuebeing assigned to attributeB of the object thatA references, instead.
Note that [PutForwards]-annotatedattributes can bechained. That is, an attribute with the [PutForwards]extended attribute can refer to an attribute that itself has that extended attribute.There must not exist a cycle in achain of forwarded assignments. A cycle exists if, when followingthe chain of forwarded assignments, a particular attribute onaninterface isencountered more than once.
An attribute with the [PutForwards]extended attribute must not also be declaredwith the [LenientSetter] or[Replaceable] extended attributes.
The [PutForwards]extended attribute must not be usedon anattribute thatis notread only.
The [PutForwards] extended attributemust not be used on astatic attribute.
The [PutForwards] extended attributemust not be used on an attribute declared onanamespace.
See theAttributes section for how[PutForwards]is to be implemented.
The followingIDL fragment defines interfaces for names and people. The [PutForwards] extended attribute is used on thename attribute of thePerson interface to indicate that assignments to that attribute result in assignments to thefull attribute of thePerson object:
[Exposed =Window ]interface Name {attribute DOMString full ;attribute DOMString family ;attribute DOMString given ;};[Exposed =Window ]interface Person { [PutForwards =full ]readonly attribute Name name ;attribute unsigned short age ;};
In the ECMAScript binding, this would allow assignments to thename property:
var p= getPerson(); // Obtain an instance of Person. p. name= 'John Citizen' ; // This statement... p. name. full= 'John Citizen' ; // ...has the same behavior as this one.
3.3.17.[Replaceable]
If the [Replaceable]extended attribute appears on aread onlyregular attribute,it indicates that setting the corresponding property on theplatform object will result inan own property with the same name being created on the objectwhich has the value being assigned. This property will shadowthe accessor property corresponding to the attribute, whichexists on theinterface prototype object.
The [Replaceable]extended attribute musttake no arguments.
An attribute with the [Replaceable]extended attribute must not also be declaredwith the [LenientSetter] or[PutForwards] extended attributes.
The [Replaceable]extended attribute must not be usedon anattribute thatis notread only.
The [Replaceable] extended attributemust not be used on astatic attribute.
The [Replaceable] extended attributemust not be used on an attribute declared onanamespace.
See§ 3.6.6 Attributes for the specific requirements that the use of[Replaceable] entails.
The followingIDL fragment defines aninterface with anoperation that increments a counter, and anattribute that exposes the counter’s value, which is initially 0:
[Exposed =Window ]interface Counter { [Replaceable ]readonly attribute unsigned long value ;void increment ();};
Assigning to thevalue property on aplatform object implementingCounter will shadow the property that corresponds to theattribute:
var counter= getCounter(); // Obtain an instance of Counter. counter. value; // Evaluates to 0. counter. hasOwnProperty( "value" ); // Evaluates to false. Object. getPrototypeOf( counter). hasOwnProperty( "value" ); // Evaluates to true. counter. increment(); counter. increment(); counter. value; // Evaluates to 2. counter. value= 'a' ; // Shadows the property with one that is unrelated // to Counter::value. counter. hasOwnProperty( "value" ); // Evaluates to true. counter. increment(); counter. value; // Evaluates to 'a'. delete counter. value; // Reveals the original property. counter. value; // Evaluates to 3.
3.3.18.[SameObject]
If the [SameObject]extended attribute appears on aread onlyattribute, then itindicates that when getting the value of the attribute on a givenobject, the same value must alwaysbe returned.
The [SameObject]extended attribute musttake no arguments.
The [SameObject]extended attribute must notbe used on anything other than aread onlyattribute whose type is aninterface type orobject.
As an example, this extended attribute is suitable for use on theimplementation attribute on theDocument interface since the same object is always returned for a givenDocument object.[DOM]
[Exposed =Window ]interface Document :Node { [SameObject ]readonly attribute DOMImplementation implementation ; // ...};
3.3.19.[SecureContext]
If the [SecureContext]extended attribute appears on aninterface,partial interface,interface mixin,partial interface mixin,callback interface,namespace,partial namespace,interface member,interface mixin member, ornamespace member,it indicates that the construct isexposed only within asecure context.The [SecureContext] extended attribute must not be usedon any other construct.
The [SecureContext] extended attribute musttake no arguments.
A construct isavailable in both secure and non-secure contexts if it is notavailable only in secure contexts (i.e., if no [SecureContext] extended attribute appliesto it).
To check if a constructC isavailable only in secure contexts, run the following steps:
Assert:C is aninterface,callback interface,namespace,interface member,interface mixin member, ornamespace member.
LetH beC’shost interface ifC is aninterface mixin member, or null otherwise.
IfC is aninterface member,interface mixin member, ornamespace member, then:
If the [
SecureContext]extended attribute is specified onC,then return true.Otherwise, setC to be theinterface,partial interface,interface mixin,partial interface mixin,namespace, orpartial namespaceC is declared on.
IfC is apartial interface,partial interface mixin, orpartial namespace, then:
If the [
SecureContext]extended attribute is specified onC,then return true.Otherwise, setC to be the originalinterface,interface mixin, ornamespace definition ofC.
IfC is aninterface mixin, then:
If the [
SecureContext]extended attribute is specified onC,then return true.Otherwise, setC toH.
Assert:C is aninterface,callback interface ornamespace.
If the [
SecureContext]extended attribute is specified onC,then return true.Otherwise, return false.
Note: Whether a construct isavailable only in secure contexts influences whether it isexposed in a givenRealm.
If [SecureContext] appears on anoverloadedoperation,then it must appear on all overloads.
The [SecureContext]extended attribute must not be specified both on
aninterface member and itsinterface orpartial interface;
aninterface mixin member and itsinterface mixin orpartial interface mixin;
anamespace member and itsnamespace orpartial namespace.
Note: This is because adding the [SecureContext]extended attribute on amember whenits containing definition is also annotated with the [SecureContext]extended attribute does not further restrict the exposure of themember.
Aninterface without the [SecureContext]extended attribute must notinherit from another interfacethat does specify [SecureContext].
The followingIDL fragment defines an interface with oneoperation that is executable from all contexts, and two which are executable only from secure contexts.
[Exposed =Window ]interface PowerfulFeature { // This call will succeed in all contexts.Promise <Result >calculateNotSoSecretResult (); // This operation will not be exposed to a non-secure context. In such a context, // there will be no "calculateSecretResult" property on PowerfulFeature.prototype. [SecureContext ]Promise <Result >calculateSecretResult (); // The same applies here: the attribute will not be exposed to a non-secure context, // and in a non-secure context there will be no "secretBoolean" property on // PowerfulFeature.prototype. [SecureContext ]readonly attribute boolean secretBoolean ;};// HeartbeatSensor will not be exposed in a non-secure context, nor will its members.// In such a context, there will be no "HeartbeatSensor" property on Window.[SecureContext ]interface HeartbeatSensor {Promise <float >getHeartbeatsPerMinute ();};// The interface mixin members defined below will never be exposed in a non-secure context,// regardless of whether the interface that includes them is.// In a non-secure context, there will be no "snap" property on// PowerfulFeature.prototype.[SecureContext ]interface mixin Snapshotable {Promise <boolean >snap ();};PowerfulFeature includes Snapshotable ;// On the other hand, the following interface mixin members will be exposed// to a non-secure context when included by a host interface// that doesn’t have the [SecureContext] extended attribute.// In a non-secure context, there will be a "log" property on// PowerfulFeatures.prototype.interface mixin Loggable {Promise <boolean >log ();};PowerfulFeatures includes Loggable ;
3.3.20.[TreatNonObjectAsNull]
The [TreatNonObjectAsNull]extended attribute is an undesirable feature. It exists only so that legacy Web platform features can be specified. It should not be used in specifications unless required to specify the behavior of legacy APIs, or for consistency with these APIs. Editors who wish to use this feature are strongly advised to discuss this byfiling an issue before proceeding.
The [TreatNonObjectAsNull]extended attribute appears on thecallback functionsEventHandlerNonNull,OnBeforeUnloadEventHandlerNonNull, andOnErrorEventHandlerNonNull used as the type ofevent handler IDL attributes such asonclick andonerror.[HTML]
If the [TreatNonObjectAsNull]extended attribute appears on acallback function,then it indicates that any value assigned to anattribute whose type is anullablecallback function that is not an object will be converted tothe
See§ 3.2.19 Nullable types — T? for the specific requirements that the use of[TreatNonObjectAsNull] entails.
The followingIDL fragment defines an interface that has one attribute whose type is a [TreatNonObjectAsNull]-annotatedcallback function and another whose type is acallback function without theextended attribute:
callback OccurrenceHandler =void (DOMString details );[TreatNonObjectAsNull ]callback ErrorHandler =void (DOMString details );[Exposed =Window ]interface Manager {attribute OccurrenceHandler ?handler1 ;attribute ErrorHandler ?handler2 ;};
In an ECMAScript implementation, assigning a value that is not an object (such as a Number value) to handler1 will have different behavior from that when assigning to handler2:
var manager= getManager(); // Get an instance of Manager. manager. handler1= function () { }; manager. handler1; // Evaluates to the function. try { manager. handler1= 123 ; // Throws a TypeError. } catch ( e) { } manager. handler2= function () { }; manager. handler2; // Evaluates to the function. manager. handler2= 123 ; manager. handler2; // Evaluates to null.
3.3.21.[TreatNullAs]
The [TreatNullAs]extended attribute is an undesirable feature. It exists only so that legacy Web platform features can be specified. It should not be used in specifications unless required to specify the behavior of legacy APIs, or for consistency with these APIs. Editors who wish to use this feature are strongly advised to discuss this byfiling an issue before proceeding.
If the [TreatNullAs]extended attribute appears on theDOMString type, it creates a newIDL type such that that when an ECMAScriptnull", which is the default, it will be converted to the empty string.
The [TreatNullAs] extended attribute musttake the identifierEmptyString.
The [TreatNullAs] extended attribute must not beassociated with a type that is notDOMString.
Note: This means that evenDOMString? must not use [TreatNullAs], since
See§ 3.2.9 DOMString for the specific requirements that the use of [TreatNullAs] entails.
[Exposed =Window ]interface Dog {attribute DOMString name ;attribute [TreatNullAs =EmptyString ]DOMString owner ;boolean isMemberOfBreed ([TreatNullAs =EmptyString ]DOMString breedName );};
An ECMAScript implementation implementing theDog interface would convert aowner property or passed as the argument to theisMemberOfBreed function to the empty string rather than "null":
var d= getDog(); // Assume d is a platform object implementing the Dog // interface. d. name= null ; // This assigns the string "null" to the .name // property. d. owner= null ; // This assigns the string "" to the .owner property. d. isMemberOfBreed( null ); // This passes the string "" to the isMemberOfBreed // function.
3.3.22.[Unforgeable]
If the [Unforgeable]extended attribute appears onregular attributes or non-staticoperations,it indicates that the attribute or operationwill be reflected as an ECMAScript propertyin a way that means its behavior cannot be modifiedand that performing a property lookup on the objectwill always result in the attribute’s property value being returned.In particular, the property will be non-configurableand will exist as an own property on the object itselfrather than on its prototype.
An attribute or operation is said to beunforgeable on a given interfaceA if the attribute or operation is declared onA,and is annotated with the [Unforgeable]extended attribute.
The [Unforgeable] extended attribute musttake no arguments.
The [Unforgeable]extended attribute must not appearon anything other than aregular attribute or a non-staticoperation.If it does appear on anoperation,then it must appear on all operationswith the sameidentifier on that interface.
The [Unforgeable] extended attribute must not be usedon an attribute declared on anamespace.
If an attribute or operationX isunforgeable on an interfaceA,andA is one of theinherited interfaces of another interfaceB,thenB must not have aregular attribute or non-staticoperation with the sameidentifier asX.
For example, the following is disallowed:
[Exposed =Window ]interface A1 { [Unforgeable ]readonly attribute DOMString x ;};[Exposed =Window ]interface B1 :A1 {void x (); // Invalid; would be shadowed by A1’s x.};[Exposed =Window ]interface B2 :A1 { };B2 includes M1 ;interface mixin M1 {void x (); // Invalid; B2’s copy of x would be shadowed by A1’s x.};
See§ 3.6.6 Attributes,§ 3.6.7 Operations,§ 3.7 Platform objects implementing interfaces,§ 3.8 Legacy platform objects and§ 3.8.3 [[DefineOwnProperty]] for the specific requirements that the use of[Unforgeable] entails.
The followingIDL fragment defines an interface that has twoattributes, one of which is designated as [Unforgeable]:
[Exposed =Window ]interface System { [Unforgeable ]readonly attribute DOMString username ;readonly attribute long long loginTime ;};
In an ECMAScript implementation of the interface, the username attribute will be exposed as a non-configurable property on the object itself:
var system= getSystem(); // Get an instance of System. system. hasOwnProperty( "username" ); // Evaluates to true. system. hasOwnProperty( "loginTime" ); // Evaluates to false. System. prototype. hasOwnProperty( "username" ); // Evaluates to false. System. prototype. hasOwnProperty( "loginTime" ); // Evaluates to true. try { // This call would fail, since the property is non-configurable. Object. defineProperty( system, "username" , { value: "administrator" }); } catch ( e) { } // This defineProperty call would succeed, because System.prototype.loginTime // is configurable. var forgedLoginTime= 5 ; Object. defineProperty( System. prototype, "loginTime" , { value: forgedLoginTime}); system. loginTime; // So this now evaluates to forgedLoginTime.
3.3.23.[Unscopable]
If the [Unscopable]extended attribute appears on aregular attribute orregular operation, itindicates that an object thatimplements an interface with the giveninterface member will not include its property name in any objectenvironment record with it as its base object. The result of this isthat bare identifiers matching the property name will not resolve tothe property in awith statement. This is achieved byincluding the property name on theinterface prototype object’s@@unscopables property’s value.
The [Unscopable]extended attribute musttake no arguments.
The [Unscopable]extended attribute must not appear onanything other than aregular attribute orregular operation.
The [Unscopable] extended attribute must not be used on an attribute declared on anamespace.
See§ 3.6.3 Interface prototype object for the specific requirements that the use of[Unscopable] entails.
For example, with the following IDL:
[Exposed =Window ]interface Thing {void f (); [Unscopable ]g ();};
thef property can be referenced with a bare identifier in awith statement but theg property cannot:
var thing= getThing(); // An instance of Thing with ( thing) { f; // Evaluates to a Function object. g; // Throws a ReferenceError. }
3.4.Security
Certain algorithms in the sections below are defined toperform a security check on a givenobject. This check is used to determine whether a givenoperation invocation orattribute access should beallowed. The security check takes the following three inputs:
theplatform object onwhich the operation invocation or attribute access is being done,
theidentifier of the operation or attribute, and
the type of thefunction object –"
method" (when it corresponds to an IDL operation), or"getter" or "setter" (when it corresponds to thegetter or setter function of an IDL attribute).
Note: The HTML Standard defines how a security check is performed.[HTML]
3.5.Overload resolution algorithm
In order to define how function invocations are resolved, theoverload resolution algorithm is defined. Its input is aneffective overload set,S, and a list of ECMAScript values,args. Its output is a pair consisting of theoperation orextended attribute of one ofS’s entries and a list of IDL values or the special value “missing”. The algorithm behaves as follows:
Letmaxarg be the length of the longest type list of the entries inS.
Letn be thesize ofargs.
Initializeargcount to be min(maxarg,n).
Remove fromS all entries whose type list is not of lengthargcount.
Initialized to −1.
Initializemethod to
undefined .If there is more than one entry inS, then setd to be thedistinguishing argument index for the entries ofS.
Initializevalues to be an empty list, where each entry will be either an IDL value or the special value “missing”.
Initializei to 0.
Whilei <d:
LetV beargs[i].
Lettype be the type at indexi in the type list of any entry inS.
Note: All entries inS at this point have the same type andoptionality value at indexi.
Letoptionality be the value at indexi in the list ofoptionality values of any entry inS.
Ifoptionality is “optional” andV is
undefined , then:If the argument at indexi is declared with adefault value,then append tovalues that default value.
Otherwise, append tovalues the special value “missing”.
Otherwise, append tovalues the result ofconvertingV to IDL typetype.
Seti toi + 1.
Ifi =d, then:
LetV beargs[i].
Note: This is the argument that will be used to resolve which overload is selected.
IfV is
undefined , and there is an entry inS whose list ofoptionality values has “optional” at indexi,then remove fromS all other entries.Otherwise: ifV is
null orundefined ,and there is an entry inS that has one of the following types at positioni of its type list,anannotated type whoseinner type is one of the above types
aunion type orannotated union type thatincludes a nullable type or thathas adictionary type in itsflattened members
then remove fromS all other entries.
Otherwise: ifVis a platform object, andthere is an entry inS that has one of the following types at positioni of its type list,
aninterface type thatVimplements
anullable version of any of the above types
anannotated type whoseinner type is one of the above types
aunion type,nullable union type, orannotated union typethat has one of the above types in itsflattened member types
then remove fromS all other entries.
Otherwise: ifType(V) is Object,V has an [[ArrayBufferData]]internal slot, andthere is an entry inS that has one of the following types at positioni of its type list,
anullable version of either of the above types
anannotated type whoseinner type is one of the above types
aunion type,nullable union type, orannotated union typethat has one of the above types in itsflattened member types
then remove fromS all other entries.
Otherwise: ifType(V) is Object,V has a [[DataView]]internal slot, andthere is an entry inS that has one of the following types at positioni of its type list,
anullable version of either of the above types
anannotated type whoseinner type is one of the above types
aunion type,nullable union type, orannotated union typethat has one of the above types in itsflattened member types
then remove fromS all other entries.
Otherwise: ifType(V) is Object,V has a [[TypedArrayName]]internal slot, andthere is an entry inS that has one of the following types at positioni of its type list,
atyped array type whose nameis equal to the value ofV’s [[TypedArrayName]]internal slot
anullable version of either of the above types
anannotated type whoseinner type is one of the above types
aunion type,nullable union type, orannotated union typethat has one of the above types in itsflattened member types
then remove fromS all other entries.
Otherwise: ifIsCallable(V) is true,and there is an entry inS that has one of the following types at positioni of its type list,
acallback function type
anullable version of any of the above types
anannotated type whoseinner type is one of the above types
aunion type,nullable union type, orannotated union typethat has one of the above types in itsflattened member types
then remove fromS all other entries.
Otherwise: ifType(V) is Object andthere is an entry inS that has one of thefollowing types at positioni of its type list,
anullable version of any of the above types
anannotated type whoseinner type is one of the above types
aunion type,nullable union type, orannotated union typethat has one of the above types in itsflattened member types
and after performing the following steps,
Letmethod be?GetMethod(V,
@@iterator).
method is not
undefined , then remove fromS allother entries.Otherwise: ifType(V) is Object andthere is an entry inS that has one of the following types at positioni of its type list,
anullable version of any of the above types
anannotated type whoseinner type is one of the above types
aunion type,nullable union type, orannotated union typethat has one of the above types in itsflattened member types
then remove fromS all other entries.
Otherwise: ifType(V) is Booleanand there is an entry inS that has one of the following types at positioni of its type list,
anannotated type whoseinner type is one of the above types
aunion type,nullable union type, orannotated union typethat has one of the above types in itsflattened member types
then remove fromS all other entries.
Otherwise: ifType(V) is Numberand there is an entry inS that has one of the following types at positioni of its type list,
anannotated type whoseinner type is one of the above types
aunion type,nullable union type, orannotated union typethat has one of the above types in itsflattened member types
then remove fromS all other entries.
Otherwise: if there is an entry inS that has one of the following types at positioni of its type list,
anullable version of any of the above types
anannotated type whoseinner type is one of the above types
aunion type,nullable union type, orannotated union typethat has one of the above types in itsflattened member types
then remove fromS all other entries.
Otherwise: if there is an entry inS that has one of the following types at positioni of its type list,
anannotated type whoseinner type is one of the above types
aunion type,nullable union type, orannotated union typethat has one of the above types in itsflattened member types
then remove fromS all other entries.
Otherwise: if there is an entry inS that has one of the following types at positioni of its type list,
anannotated type whoseinner type is one of the above types
aunion type,nullable union type, orannotated union typethat has one of the above types in itsflattened member types
then remove fromS all other entries.
Otherwise: if there is an entry inS that has
anyat positioni of its type list, then remove fromS all other entries.
Letcallable be theoperation orextended attribute of the single entry inS.
Ifi =d andmethod is not
undefined , thenLetV beargs[i].
LetT be the type at indexi in thetype list of the remaining entry inS.
IfT is asequence type, thenappend tovalues the result ofcreating a sequence of typeT fromV andmethod.
Otherwise,T is afrozen array type.Append tovalues the result ofcreating a frozen array of type T from V and method.
Seti toi + 1.
Whilei <argcount:
LetV beargs[i].
Lettype be the type at indexi in the type list of the remaining entry inS.
Letoptionality be the value at indexi in the list ofoptionality values of the remaining entry inS.
Ifoptionality is “optional” andV is
undefined , then:If the argument at indexi is declared with adefault value,then append tovalues that default value.
Otherwise, append tovalues the special value “missing”.
Otherwise, append tovalues the result ofconvertingV to IDL typetype.
Seti toi + 1.
Whilei is less than the number of argumentscallable is declared to take:
Ifcallable’s argument at indexi is declared with adefault value,then append tovalues that default value.
Otherwise, ifcallable’s argument at indexi is not variadic, then append tovalues the special value “missing”.
Seti toi + 1.
Return the pair <callable,values>.
The overload resolution algorithm performs both the identification of which overloaded operation, constructor, etc. is being called, and the conversion of the ECMAScript argument values to their corresponding IDL values. Informally, it operates as follows.
First, the selection of valid overloads is done by considering the number of ECMAScript arguments that were passed in to the function:
If there are more arguments passed in than the longestoverload argument list, then they are ignored.
After ignoring these trailing arguments, only overloadsthat can take this exact number of arguments are considered.If there are none, then a
TypeErroris thrown.
Once we have a set of possible overloads with the right number of arguments, the ECMAScript values are converted from left to right. The nature of the restrictions on overloading means that if we have multiple possible overloads at this point, then there will be one position in the argument list that will be used to distinguish which overload we will finally select; this is thedistinguishing argument index.
We first convert the arguments to the left of the distinguishing argument. (There is a requirement that an argument to the left of the distinguishing argument index has the same type as in the other overloads, at the same index.) Then we inspect the type of the ECMAScript value that is passed in at the distinguishing argument index to determine which IDL type it may correspond to. This allows us to select the final overload that will be invoked. If the value passed in isTypeError. The inspection of the value at the distinguishing argument index does not have any side effects; the only side effects that come from running the overload resolution algorithm are those that come from converting the ECMAScript values to IDL values.
At this point, we have determined which overload to use. We now convert the remaining arguments, from the distinguishing argument onwards, again ignoring any additional arguments that were ignored due to being passed after the last possible argument.
When converting an optional argument’s ECMAScript value to its equivalent IDL value,
Optional arguments corresponding to a final, variadic argument do not treat
3.6.Interfaces
For everyinterface that isexposed ina givenRealm and that is not declared withthe [NoInterfaceObject] or [LegacyNamespace]extended attributes,a corresponding property exists on theRealm'sglobal object.The name of the property is theidentifier of the interface,and its value is an object called theinterface object.The characteristics of an interface object are described in§ 3.6.1 Interface object.
If the [LegacyWindowAlias] extended attribute was specified on anexposed interface,then for eachidentifier in [LegacyWindowAlias]'sidentifiers there exists a corresponding property on theWindow global object.The name of the property is the givenidentifier,and its value is a reference to theinterface object for theinterface.
In addition, for every [NamedConstructor] extended attribute on anexposed interface,a corresponding property exists on the ECMAScript global object.The name of the property is the [NamedConstructor]'sidentifier,and its value is an object called anamed constructor,which allows construction of objects that implement the interface.The characteristics of a named constructor are described in§ 3.6.2 Named constructors.
3.6.1.Interface object
Theinterface object for a giveninterface is abuilt-in function object.It has properties that correspond to theconstants andstatic operations defined on that interface,as described in sections§ 3.6.5 Constants and§ 3.6.7 Operations.
If theinterface is declared with aconstructor operation,then theinterface object can be called as aconstructor to create an object thatimplements that interface.Calling that interface as a function will throw an exception.
Interface objects whoseinterfaces are not declaredwith aconstructor operation will throw when called,both as a function and as aconstructor.
Aninterface object for aninterface has an associated object called theinterface prototype object.This object has properties that correspond totheregular attributes andregular operations defined on the interface,and is described in more detail in§ 3.6.3 Interface prototype object.
Note: Since aninterface object is afunction object thetypeof operator will return "function" when applied to an interface object.
An interface may haveoverridden constructor steps, which canchange the behavior of theinterface object when called or constructed. Bydefault interfaces do not have such steps.
In general, constructors are described by defining aconstructor operation and its behavior. Theoverridden constructor steps are used only for more complicated situations. Editors who wish to use this feature are strongly advised to discuss this byfiling an issue before proceeding.
Theinterface object for a giveninterfaceI withidentifierid and inRealmrealm iscreated as follows:
Letsteps beI’soverridden constructor steps if they exist, orthe following steps otherwise:
IfI was not declared with aconstructor operation,thenthrow a
TypeError.Letargs be the passed arguments.
Letn be thesize ofargs.
Letid be the identifier of interfaceI.
Compute the effective overload set for constructors withidentifierid oninterfaceI and with argument countn, and letS be the result.
Let <constructor,values> be the resultof passingS andargs.to theoverload resolution algorithm.
Letobject be the result ofinternally creating a new object implementingI, withrealm and
NewTarget.Perform the actions listed in the description ofconstructor withvalues as the argument valuesandobject asthis.
LetO beobject,converted to an ECMAScript value.
Assert:O is an object thatimplementsI.
Assert:O.[[Realm]] isrealm.
ReturnO.
LetconstructorProto berealm.[[Intrinsics]].[[
%FunctionPrototype%]].IfI inherits from some other interfaceP,then setconstructorProto to theinterface object ofP inrealm.
LetF be!CreateBuiltinFunction(steps, « [[Unforgeables]] »,realm,constructorProto).
Letunforgeables beObjectCreate(
null ).Define the unforgeable regular operations ofI onunforgeables, givenrealm.
Define the unforgeable regular attributes ofI onunforgeables, givenrealm.
SetF.[[Unforgeables]] tounforgeables.
Note: this object is never exposed to user code. It exists only to ensure all instancesof an interface with an unforgeable member use the same JavaScript function objects forattribute getters,attribute setters andoperation functions.
Perform!SetFunctionName(F,id).
Letlength be 0.
IfI was declared with aconstructor operation, then
Compute the effective overload set for constructors withidentifierid oninterfaceI and with argument count 0, and letS be the result.
Setlength to the length of theshortest argument list of the entries inS.
Perform!SetFunctionLength(F,length).
Letproto be the result ofcreating an interfaceprototype object ofinterfaceI inrealm.
Perform!DefinePropertyOrThrow(F, "
prototype",PropertyDescriptor{[[Value]]:proto, [[Writable]]:false , [[Enumerable]]:false , [[Configurable]]:false }).Define the constants ofinterfaceI onF givenrealm.
Define the static attributes ofinterfaceI onF givenrealm.
Define the static operations ofinterfaceI onF givenrealm.
ReturnF.
3.6.2.Named constructors
Anamed constructor that exists due to one or more[NamedConstructor]extended attributes with a givenidentifier is abuilt-in function object.It allows constructing objects thatimplement the interface on which the[NamedConstructor] extended attributes appear.
Thenamed constructor withidentifierid for a giveninterfaceI in Realmrealm iscreated as follows:
Letsteps be the following steps:
Letargs be the passed arguments.
Letn be thesize ofargs.
Compute the effective overload set for named constructors withidentifierid oninterfaceI and with argument countn, and letS be the result.
Let <constructor,values> be the result of passingS andargs to theoverload resolution algorithm.
Letobject be the result ofinternally creating a new object implementingI, withrealm and
NewTarget.Perform the actions listed in the description ofconstructor withvalues as the argument valuesandobject asthis.
LetO beobject,converted to an ECMAScript value.
Assert:O is an object thatimplementsI.
Assert:O.[[Realm]] isrealm.
ReturnO.
LetF be!CreateBuiltinFunction(steps, « »,realm).
Perform!SetFunctionName(F,id).
Compute the effective overload set for named constructors withidentifierid oninterfaceI and with argument count 0, and letS be the result.
Letlength be the length of the shortest argument list of the entries inS.
Perform!SetFunctionLength(F,length).
Letproto be theinterface prototype object ofinterfaceI inrealm.
Perform!DefinePropertyOrThrow(F, "
prototype",PropertyDescriptor{[[Value]]:proto, [[Writable]]:false , [[Enumerable]]:false , [[Configurable]]:false }).ReturnF.
3.6.3.Interface prototype object
There will exist aninterface prototype object for everyinterface defined,regardless of whether the interface was declaredwith the [NoInterfaceObject]extended attribute.
Theinterface prototype object for a giveninterfaceinterface andRealmrealm iscreated as follows:
Letproto be null.
Ifinterface is declared with the [
Global]extended attribute,andinterfacesupports named properties,then setproto to the result ofcreating a namedproperties object forinterface andrealm.Otherwise, ifinterface is declared to inherit from another interface,then setproto to theinterface prototype object inrealm of thatinherited interface.
Otherwise, ifinterface is the
DOMExceptioninterface,then setproto torealm.[[Intrinsics]].[[%ErrorPrototype%]].Otherwise, setproto torealm.[[Intrinsics]].[[
%ObjectPrototype%]].Assert:Type(proto) is Object.
LetinterfaceProtoObj be!ObjectCreate(proto).
Ifinterface has anymember declared with the [
Unscopable]extended attribute,then:Should an
@@unscopablesproperty also be defined ifinterface isdeclared with the [Global]extended attribute?This is discussed inissue #544.LetunscopableObject be the result of performing!ObjectCreate(
null ).For eachexposedmembermember ofinterface that is declared with the [
Unscopable]extended attribute:Letid bemember’sidentifier.
Perform!CreateDataProperty(unscopableObject,id,
true ).
Letdesc be the PropertyDescriptor{[[Value]]:unscopableObject,[[Writable]]:
false , [[Enumerable]]:false ,[[Configurable]]:true }.Perform!DefinePropertyOrThrow(interfaceProtoObj,
@@unscopables,desc).
Ifinterface is declared with the [
Global]extended attribute, orinterface is in the set ofinherited interfaces of an interfacethat is declared with the [Global]extended attribute, then:Set the internal methods ofinterfaceProtoObj which are specific toimmutable prototype exotic objects to the definitions specified inECMA-262 Immutable prototype exotic objects.
Ifinterface is not declared with the [
Global]extended attribute, then:Define the regular attributes ofinterface oninterfaceProtoObj givenrealm.
Define the regular operations ofinterface oninterfaceProtoObj givenrealm.
Define the constants ofinterface oninterfaceProtoObj givenrealm.
If the [
NoInterfaceObject]extended attribute was not specified oninterface, then:Letconstructor be theinterface object ofinterface inrealm.
Letdesc be the PropertyDescriptor{[[Writable]]:
true ,[[Enumerable]]:false , [[Configurable]]:true ,[[Value]]:constructor}.Perform!DefinePropertyOrThrow(interfaceProtoObj, "
constructor",desc).
ReturninterfaceProtoObj.
Additionally,interface prototype objects get properties declaratively from:
Define those properties imperatively instead.
Theinterface prototype object of aninterface that is defined with the [NoInterfaceObject]extended attribute will be accessible. For example, with the following IDL:
[Exposed =Window ,NoInterfaceObject ]interface Foo {};partial interface Window {attribute Foo foo ;};
it is not possible to access the interface prototype object through theinterface object (since it does not exist aswindow.Foo). However, an instance ofFoo can expose the interface prototype object by calling its [[GetPrototypeOf]]internal method –Object.getPrototypeOf(window.foo) in this example.
Theclass string of aninterface prototype object is the concatenation oftheinterface’squalified name and the string "Prototype".
3.6.4.Named properties object
For everyinterface declared with the [Global]extended attribute thatsupports named properties,there will exist an object known as thenamed properties object for that interface on which named properties are exposed.
Letproto be null.
Ifinterface is declared to inherit from another interface,then setproto to theinterface prototype object inrealm for theinherited interface.
Otherwise, setproto torealm.[[Intrinsics]].[[
%ObjectPrototype%]].Letobj be a newly created object.
Setobj’s internal methods to the definitions specified inECMA-262 Ordinary object internal methods and internal slots,unless they are specified in the the rest of§ 3.6.4 Named properties object.
Setobj’s remaining internal methods to the definitions specified below.
Setobj.[[Prototype]] toproto.
Setobj.[[Extensible]] to
true .Returnobj.
Theclass string of anamed properties object is the concatenation of theinterface’sidentifier and the string "Properties".
3.6.4.1.[[GetOwnProperty]]
When the [[GetOwnProperty]] internal method of anamed properties objectO is called with property keyP, the following steps are taken:
LetA be theinterface for thenamed properties objectO.
Letobject beO.[[Realm]]'sglobal object.
Assert:objectimplementsA.
If the result of running thenamed property visibility algorithm withproperty nameP and objectobject is true, then:
Letoperation be the operation used to declare the named property getter.
Letvalue be an uninitialized variable.
Ifoperation was defined without anidentifier, thensetvalue to the result of performing the steps listed in the interface description todetermine the value of a named property withP as the name.
Otherwise,operation was defined with an identifier. Setvalue to the resultof performing the steps listed in the description ofoperation withP as the only argument value.
Letdesc be a newly createdProperty Descriptor with no fields.
Setdesc.[[Value]] to the result ofconvertingvalue to an ECMAScript value.
IfAimplements an interface with the[
LegacyUnenumerableNamedProperties]extended attribute,then setdesc.[[Enumerable]] tofalse ,otherwise set it totrue .Setdesc.[[Writable]] to
true anddesc.[[Configurable]] totrue .Returndesc.
ReturnOrdinaryGetOwnProperty(O,P).
3.6.4.2.[[DefineOwnProperty]]
When the [[DefineOwnProperty]] internal method of anamed properties object is called, the following steps are taken:
Return
false .
3.6.4.3.[[Delete]]
When the [[Delete]] internal method of anamed properties object is called, the following steps are taken:
Return
false .
3.6.4.4.[[SetPrototypeOf]]
When the [[SetPrototypeOf]] internal method of anamed properties objectO is called with ECMAScript language valueV, the following step is taken:
Return?SetImmutablePrototype(O,V).
3.6.4.5.[[PreventExtensions]]
When the [[PreventExtensions]] internal method of anamed properties object is called, the following steps are taken:
Return
false .
Note: this keepsnamed properties object extensible by making [[PreventExtensions]] fail.
3.6.5.Constants
Constants are exposed oninterface objects,legacy callback interface objects,interface prototype objects, andon the single object thatimplements the interface,when an interface is declared with the [Global]extended attribute.
For eachconstantconst that is amember ofdefinition:
Letvalue be the result ofconvertingconst’s IDL value to an ECMAScript value.
Letdesc be the PropertyDescriptor{[[Writable]]:
false ,[[Enumerable]]:true , [[Configurable]]:false ,[[Value]]:value}.Letid beconst’sidentifier.
Perform!DefinePropertyOrThrow(target,id,desc).
3.6.6.Attributes
Static attributes are exposed on theinterface object.Regular attributes are exposed on theinterface prototype object,unless the attribute isunforgeable orif the interface was declared with the [Global]extended attribute,in which case they are exposed on every object thatimplements the interface.
Letattributes be thelist ofregular attributes that aremembers ofdefinition.
Remove fromattributes all theattributes that areunforgeable.
Define the attributesattributes ofdefinition ontarget givenrealm.
Letattributes be thelist ofstatic attributes that aremembers ofdefinition.
Define the attributesattributes ofdefinition ontarget givenrealm.
Letattributes be thelist ofunforgeableregular attributes that aremembers ofdefinition.
Define the attributesattributes ofdefinition ontarget givenrealm.
For eachattributeattr ofattributes:
Letgetter be the result of creating anattribute getter givenattr,definition, andrealm.
Letsetter be the result of creating anattribute setter givenattr,definition, andrealm.
Note: the algorithm to create anattribute setter returns
undefined ifattr isread only.Letconfigurable be
false ifattr isunforgeable andtrue otherwise.Letdesc be the PropertyDescriptor{[[Get]]:getter, [[Set]]:setter,[[Enumerable]]:
true , [[Configurable]]:configurable}.Letid beattr’sidentifier.
Perform!DefinePropertyOrThrow(target,id,desc).
Theattribute getter is created as follows, given anattributeattribute, anamespace orinterfacetarget, and aRealmrealm:
Letsteps be the following series of steps:
Try running the following steps:
LetidlObject be null.
Iftarget is aninterface, andattribute is aregular attribute:
LetesValue be the
this value, if it is notnull orundefined , orrealm’sglobal object otherwise.(This will subsequently cause aTypeErrorin a few steps, ifthe global object does not implementtarget and [LenientThis] is notspecified.)IfesValueis a platform object, thenperform a security check,passingesValue,attribute’sidentifier, and "getter".
IfesValue does notimplementtarget, then:
Ifattribute was specified with the [
LenientThis]extended attribute, then returnundefined .
SetidlObject to the IDLinterface type value that represents a referencetoesValue.
LetR be the result ofgetting the underlying value ofattribute givenidlObject.
Return the result ofconvertingR to anECMAScript value of the typeattribute is declared as.
And then, ifan exceptionE was thrown:
Ifattribute’s type is apromise type, then return!Call(
%Promise_reject%,%Promise%, «E»).Otherwise, end these steps and allow the exception to propagate.
LetF be!CreateBuiltinFunction(steps, « »,realm).
Letname be the string "
get" prepended toattribute’sidentifier.Perform!SetFunctionName(F,name).
Perform!SetFunctionLength(F, 0).
ReturnF.
Theattribute setter is created as follows, given anattributeattribute, anamespace orinterfacetarget, and aRealmrealm:
Iftarget is anamespace:
Assert:attribute isread only.
Return
undefined .
Ifattribute isread only and does not have a[
LenientSetter], [PutForwards] or [Replaceable]extended attribute, returnundefined ; there is noattribute setter function.Assert:attribute’s type is not apromise type.
Letsteps be the following series of steps:
LetV be the value of the first argument passed.
Letid beattribute’sidentifier.
LetidlObject be null.
Ifattribute is aregular attribute:
LetesValue be the
this value, if it is notnull orundefined , orrealm’sglobal object otherwise.(This will subsequently cause aTypeErrorin a few steps, ifthe global object does not implementtarget and [LenientThis] is notspecified.)IfesValueis a platform object, thenperform a security check, passingesValue,id, and "setter".
LetvalidThis be true ifesValueimplementstarget, or false otherwise.
IfvalidThis is false andattribute was not specified with the [
LenientThis]extended attribute, thenthrow aTypeError.Ifattribute is declared with the [
Replaceable] extended attribute, then:Perform?CreateDataProperty(esValue,id,V).
Return
undefined .
IfvalidThis is false, then return
undefined .Ifattribute is declared with a [
LenientSetter] extended attribute, thenreturnundefined .Ifattribute is declared with a [
PutForwards] extended attribute, then:SetidlObject to the IDLinterface type value that represents a referencetoesValue.
LetidlValue be determined as follows:
- attribute’s type is anenumeration
IfS is not one of theenumeration’s values, thenreturn
undefined .Otherwise,idlValue is the enumeration value equal toS.
- Otherwise
- idlValue is the result ofconvertingV to an IDL value ofattribute’s type.
Perform the actions listed in the description ofattribute that occur on setting,withidlValue asthe given value andidlObject asthis if it is not null.
Return
undefined
LetF be!CreateBuiltinFunction(steps, « »,realm).
Letname be the string "
set" prepended toid.Perform!SetFunctionName(F,name).
Perform!SetFunctionLength(F, 1).
ReturnF.
Note: Although there is only a single property for an IDL attribute, sinceaccessor property getters and setters are passed athis value for the object on which property corresponding to the IDL attribute isaccessed, they are able to expose instance-specific data.
Note: Attempting to assign to a property corresponding to aread onlyattribute results in different behavior depending on whether the script doing so is in strict mode.When in strict mode, such an assignment will result in aTypeError being thrown. When not in strict mode, the assignment attempt will be ignored.
3.6.7.Operations
For each uniqueidentifier of anexposedoperation defined on theinterface,there exist a corresponding property.Static operations are exposed of theinterface object.Regular operations are exposed on theinterface prototype object,unless the operation isunforgeable orthe interface was declared with the [Global]extended attribute,in which case they are exposed on every object thatimplements the interface.
Letoperations be thelist ofregular operations that aremembers ofdefinition.
Remove fromoperations all theoperations that areunforgeable.
Define the operationsoperations ofdefinition ontarget givenrealm.
Letoperations be thelist ofstatic operations that aremembers ofdefinition.
Define the operationsoperations ofdefinition ontarget givenrealm.
Letoperations be thelist ofunforgeableregular operations that aremembers ofdefinition.
Define the operationsoperations ofdefinition ontarget givenrealm.
For eachoperationop ofoperations:
Letmethod be the result ofcreating an operation function givenop,definition, andrealm.
Letmodifiable be
false ifop isunforgeable andtrue otherwise.Letdesc be the PropertyDescriptor{[[Value]]:method,[[Writable]]:modifiable, [[Enumerable]]:
true ,[[Configurable]]:modifiable}.Letid beop’sidentifier.
Perform!DefinePropertyOrThrow(target,id,desc).
Letid beop’sidentifier.
Letsteps be the following series of steps, given function argumentvaluesargs:
Try running the following steps:
LetidlObject be null.
Iftarget is aninterface, andop is not astatic operation:
LetesValue be the
this value, if it is notnull orundefined , orrealm’sglobal object otherwise.(This will subsequently cause aTypeErrorin a few steps, ifthe global object does not implementtarget and [LenientThis] is notspecified.)IfesValueis a platform object, thenperform a security check,passingesValue,id, and "method".
IfesValue does notimplement the interfacetarget,throw a
TypeError.SetidlObject to the IDLinterface type value that represents a referencetoesValue.
Letn be thesize ofargs.
Compute the effective overload set forregular operations (ifop is aregular operation) or forstatic operations (ifop is a static operation)withidentifierid ontarget and with argument countn, and letS bethe result.
Let <operation,values> be the result of passingS andargs to theoverload resolution algorithm.
LetR be
null .Ifoperation is declared with a [
Default]extended attribute,then:SetR be the result of performing the actions listed inoperation’scorresponding default operation,withvalues as the argument valuesandidlObject asthis if it is not null.
Otherwise:
SetR be the result of performing the actions listed in thedescription ofoperation,withvalues as the argument valuesandidlObject asthis if it is not null.
ReturnR,converted to an ECMAScript value.
R is assumed to be an IDL value of the typeop is declared to return.<https://github.com/heycam/webidl/issues/674>
And then, ifan exceptionE was thrown:
Ifop has areturn type that is apromise type, then return!Call(
%Promise_reject%,%Promise%, «E»).Otherwise, end these steps and allow the exception to propagate.
LetF be!CreateBuiltinFunction(steps, « »,realm).
Perform!SetFunctionName(F,id).
Compute the effective overload set forregular operations (ifop is a regularoperation) or forstatic operations (ifop is a static operation) withidentifierid ontarget and with argument count 0, and letS be the result.
Letlength be the length of the shortest argument list in the entries inS.
Perform!SetFunctionLength(F,length).
ReturnF.
3.6.7.1.Default operations
Onlyregular operations which have acorresponding default operation defined belowmay be declared with a [Default]extended attribute.
3.6.7.1.1.Default toJSON operation
Thecorresponding default operation of thetoJSON operation is thedefault toJSON operation.
Thereturn type of thedefault toJSON operation must beobject.
To invoke thedefault toJSON operation ofinterfaceI, run the the following steps:
Letmap be a newordered map.
Letstack be the result ofcreating an inheritance stack forinterfaceI.
Invokecollect attribute values of an inheritance stack onthis,passing itstack andmap as arguments.
Letresult be!ObjectCreate(
%ObjectPrototype%).For eachkey →value ofmap,
Letk bekeyconverted to an ECMAScript value.
Letv bevalueconverted to an ECMAScript value.
Perform!CreateDataProperty(result,k,v).
Returnresult.
To invoke thecollect attribute values of an inheritance stack abstract operation withstackstack andordered mapmap as arguments, run the the following steps:
LetI be the result ofpopping fromstack.
Invokecollect attribute values onthis,passing itI andmap as arguments.
Ifstackis not empty,then invokecollect attribute values of an inheritance stack onthis,passing itstack andmap as arguments.
To invoke thecollect attribute values abstract operation withinterfaceI andordered mapmap as arguments, run the the following steps:
If a
toJSONoperation with a [Default]extended attribute is declared onI, thenfor eachexposedregular attributeattr that is aninterface member ofI, in order:Letid be theidentifier ofattr.
Letvalue be the result ofgetting the underlying value ofattr giventhis.
Tocreate an inheritance stack forinterfaceI, run the the following steps:
The followingIDL fragment defines a number ofinterfaces, which areinherited interfaces ofA, andinterface mixins, which areincluded byA or byA’sinherited interfaces, as show in the below inheritance tree.
C* - M4 | B - M3 |M1 - A - M2*
Interfaces andinterface mixins marked with an asterisk ("*") declare atoJSONoperation with a [Default]extended attribute.
[Exposed=Window]interface A : B { attribute DOMString a;};[Exposed=Window]interface B : C { attribute DOMString b;};[Exposed=Window]interface C { [Default] object toJSON(); attribute DOMString c;};interface mixin M1 { attribute DOMString m1;};interface mixin M2 { [Default] object toJSON(); attribute DOMString m2;};interface mixin M3 { attribute DOMString m3;};interface mixin M4 { attribute DOMString m4;};A includes M1;A includes M2;B includes M3;C includes M4;Calling thetoJSON() method of an object implementing interfaceA defined above would return the following JSON object:
{ "a" : "..." , "m1" : "..." , "m2" : "..." , "c" : "..." , "m4" : "..." }
An object implementing interfaceB would return:
{ "c" : "..." , "m4" : "..." }
3.6.7.2.Stringifiers
If theinterface has anexposedstringifier,then there must exist a property with the following characteristics:
The name of the property is "
toString".If thestringifier isunforgeable on the interfaceor if the interface was declared with the [
Global]extended attribute,then the property exists on every object thatimplements the interface.Otherwise, the property exists on theinterface prototype object.The property has attributes{ [[Writable]]:B, [[Enumerable]]:
true , [[Configurable]]:B },whereB isfalse if the stringifier isunforgeable on the interface,andtrue otherwise.The value of the property is abuilt-in function object, which behaves as follows:
LetO be the result of callingToObject on the
this value.IfOis a platform object,thenperform a security check, passing:
the platform objectO,
theidentifier of thestringifier, and
the type "
method".
IfO does notimplement theinterface on which the stringifier was declared, thenthrow a
TypeError.LetV be an uninitialized variable.
Depending on where
stringifierwas specified:- on anattribute
SetV to the result of performing the actions listed in the description of the attribute that occur when getting(or those listed in the description of the inherited attribute, if this attribute is declared toinherit its getter),withO as the object.
- on anoperation with an identifier
SetV to the result of performing the actions listed in the descriptionof the operation, usingO as the
this valueand passing no arguments.- on anoperation with no identifier
SetV to the result of performing thestringification behavior of the interface.
Return the result ofconvertingV to a String value.
The value of thefunction object’s
lengthproperty is the Number value0 .The value of thefunction object’s
nameproperty is the String value "toString".
3.6.8.Common iterator behavior
3.6.8.1.@@iterator
If theinterface has any of the following:
then a property must existwhose name is the@@iterator symbol, with attributes{ [[Writable]]:
The location of the property is determined as follows:
If the interface was declared with the [
Global]extended attribute,then the property exists on the single object thatimplements the interface.Otherwise, the property exists solely on the interface’sinterface prototype object.
If the interface defines anindexed property getter,then thefunction object is%ArrayProto_values%.
If the interface has apair iterator, then thefunction object is abuilt-in function object that, when invoked, must behave as follows:
Letobject be the result of callingToObject on the
this value.Ifobjectis a platform object,thenperform a security check, passing:
the platform objectobject,
the identifier "
@@iterator", andthe type "
method".
Letinterface be theinterface theiterable declaration is on.
Letiterator be a newly createddefault iterator object forinterface withobject as its target and iterator kind "
key+value".Returniterator.
If the interface has amaplike declaration orsetlike declaration, then thefunction object is abuilt-in function object that, when invoked, must behave as follows:
Letobject be the result of callingToObject on the
this value.Ifobjectis a platform object,thenperform a security check, passing:
the platform objectobject,
the identifier "
@@iterator", andthe type "
method".
Ifobject does notimplement theinterface on which themaplike declaration orsetlike declaration is defined,thenthrow a
TypeError.If the interface has amaplike declaration, then:
Letbacking be the value of the [[BackingMap]]internal slot ofobject.
ReturnCreateMapIterator(backing, "
key+value").
Otherwise:
Letbacking be the value of the [[BackingSet]]internal slot ofobject.
ReturnCreateSetIterator(backing, "
value").
The value of the@@iteratorfunction object’slength property is the Number value
The value of the@@iteratorfunction object’sname propertyis the String value "entries"if the interface has apair iterator or amaplike declaration and the String "values"if the interface has asetlike declaration.
3.6.8.2.@@asyncIterator
If theinterface has anasynchronously iterable declaration, then a property must existwhose name is the@@asyncIterator symbol, with attributes{ [[Writable]]:
The location of the property is determined as follows:
If the interface was declared with the [
Global]extended attribute,then the property exists on the single object thatimplements the interface.Otherwise, the property exists solely on the interface’sinterface prototype object.
Thefunction object is abuilt-in function object that, when invoked, must behave as follows:
Letobject be the result of callingToObject on the
this value.Ifobjectis a platform object, thenperform a security check, passing:
the platform objectobject,
the identifier "
@@asyncIterator", andthe type "
method".
Letinterface be theinterface on which theasynchronously iterable declaration is declared.
Letiterator be a newly createddefault asynchronous iterator object forinterface withobject as itstarget,"
key+value" as itskind, andis finished set to false.Run theasynchronous iterator initialization steps forinterface withobject anditerator, if any such steps exist.
Returniterator.
The value of the@@asyncIteratorfunction object’slength propertyis the Number value
The value of the@@asyncIteratorfunction object’sname propertyis the String value "entries".
3.6.8.3.forEach
If theinterface has any of the following:
then aforEach data property must exist with attributes{ [[Writable]]:
The location of the property is determined as follows:
If the interface was declared with the [
Global]extended attribute,then the property exists on the single object thatimplements the interface.Otherwise, the property exists solely on the interface’sinterface prototype object.
If the interface defines anindexed property getter,then thefunction object is%ArrayProto_forEach%.
If the interface has apair iterator, then the method must have the same behavior, when invoked with argumentcallback and optional argumentthisArg, as one that would exist assuming the interface had thisoperation instead of theiterable declaration:
[Exposed =Window ]interface Iterable {void forEach (Function callback ,optional any thisArg );};
with the following prose definition:
Letpairs be the list ofvalue pairs to iterate over.
Leti be 0.
Whilei is less than the length ofpairs:
Letpair be the entry inpairs at indexi.
Letkey bepair’skey.
Letvalue bepair’svalue.
Invokecallback withthisArg (or
undefined , if the argument was not supplied)as thecallback this value andvalue,key andthis as its arguments.Updatepairs to the current list ofvalue pairs to iterate over.
Seti toi + 1.
If the interface has amaplike declaration orsetlike declaration then the method, when invoked, must behave as follows:
Letobject be the result of callingToObject on the
this value.Ifobjectis a platform object,thenperform a security check, passing:
the platform objectobject,
the identifier "
forEach", andthe type "
method".
Letinterface be theinterface on which themaplike declaration orsetlike declaration is declared.
LetcallbackFn be the value of the first argument passed to the function, or
undefined if the argument was not supplied.IfIsCallable(callbackFn) is
false ,throw aTypeError.LetthisArg be the value of the second argument passed to the function, or
undefined if the argument was not supplied.Letbacking be the value of the [[BackingMap]]internal slot ofobject,if the interface has amaplike declaration,or the [[BackingSet]]internal slot ofobject otherwise.
LetcallbackWrapper be abuilt-in function object that, when invoked, behaves as follows:
Letv andk be the first two arguments passed to the function.
LetthisArg be the
this value.
Note: ThecallbackWrapper function simply calls the incomingcallbackFn withobject as the third argument rather than its internal [[BackingMap]] or [[BackingSet]] object.
Can the script author observe thatcallbackWrapper might be a new function every time forEach is called? What’s the best way of specifying that there’s only one function that has captured an environment?
Return
undefined .
The value of thefunction object’slength property is the Number value
The value of thefunction object’sname property is the String value "forEach".
3.6.9.Iterable declarations
3.6.9.1.entries
If theinterface has aniterable declaration or anasynchronously iterable declaration,then anentries data property must exist with attributes{ [[Writable]]:
The location of the property is determined as follows:
If the interface was declared with the [
Global]extended attribute,then the property exists on the single object thatimplements the interface.Otherwise, the property exists solely on the interface’sinterface prototype object.
If the interface has avalue iterator,then thefunction object is%ArrayProto_entries%.
If the interface has apair iterator,then thefunction object isthe value of the@@iterator property.
If the interface has anasynchronously iterable declaration, then thefunction object isthe value of the@@asyncIterator property.
3.6.9.2.keys
If theinterface has aniterable declaration or anasynchronously iterable declaration,then akeys data property must exist with attributes{ [[Writable]]:
The location of the property is determined as follows:
If the interface was declared with the [
Global]extended attribute,then the property exists on the single object thatimplements the interface.Otherwise, the property exists solely on the interface’sinterface prototype object.
If the interface has avalue iterator,then thefunction object is%ArrayProto_keys%.
If the interface has apair iterator, then the method, when invoked, must behave as follows:
Letobject be the result of callingToObject on the
this value.Ifobjectis a platform object,thenperform a security check, passing:
the platform objectobject,
the identifier "
keys", andthe type "
method".
Letinterface be theinterface on which theiterable declaration is declared.
Letiterator be a newly createddefault iterator object forinterface withobject as its target and iterator kind "
key".Returniterator.
If the interface has anasynchronously iterable declaration, then the method, when invoked, must behave as follows:
Letobject be the result of callingToObject on the
this value.Ifobjectis a platform object, thenperform a security check, passing:
the platform objectobject,
the identifier "
keys", andthe type "
method".
Letinterface be theinterface on which theasynchronously iterable declaration is declared.
Letiterator be a newly createddefault asynchronous iterator object forinterface withobject as itstarget,"
key" as itskind, andis finished set to false.Run theasynchronous iterator initialization steps forinterface withobject anditerator, if any such steps exist.
Returniterator.
The value of thefunction object’slength property is the Number value
The value of thefunction object’sname property is the String value "keys".
3.6.9.3.values
If theinterface has aniterable declaration or anasynchronously iterable declaration,then avalues data property must existwith attributes { [[Writable]]:
The location of the property is determined as follows:
If the interface was declared with the [
Global]extended attribute,then the property exists on the single object thatimplements the interface.Otherwise, the property exists solely on the interface’sinterface prototype object.
If the interface has avalue iterator,then thefunction object isthe value of the@@iterator property.
If the interface has apair iterator, then the method, when invoked, must behave as follows:
Letobject be the result of callingToObject on the
this value.Ifobjectis a platform object,thenperform a security check, passing:
the platform objectobject,
the identifier "
entries", andthe type "
method".
Letinterface be theinterface on which theiterable declaration is declared.
Letiterator be a newly createddefault iterator object forinterface withobject as its target and iterator kind "
value".Returniterator.
If the interface has anasynchronously iterable declaration, then the method, when invoked, must behave as follows:
Letobject be the result of callingToObject on the
this value.Ifobjectis a platform object, thenperform a security check, passing:
the platform objectobject,
the identifier "
entries", andthe type "
method".
Letinterface be theinterface on which theasynchronously iterable declaration is declared.
Letiterator be a newly createddefault asynchronous iterator object forinterface withobject as itstarget,"
value" as itskind, andis finished set to false.Run theasynchronous iterator initialization steps forinterface withobject anditerator, if any such steps exist.
Returniterator.
The value of thefunction object’slength property is the Number value
The value of thefunction object’sname property is the String value "values".
3.6.9.4.Default iterator objects
Adefault iterator object for a giveninterface, target and iteration kindis an object whose [[Prototype]]internal slot is theiterator prototype object for theinterface.
Adefault iterator object has three internal values:
itstarget, which is an object whose values are to be iterated,
itskind, which is the iteration kind,
itsindex, which is the current index into the values value to be iterated.
Note: Default iterator objects are only used forpair iterators;value iterators, as they are currentlyrestricted to iterating over an object’ssupported indexed properties,use standard ECMAScript Array iterator objects.
When adefault iterator object is first created,its index is set to 0.
Default iterator objects do not haveclass strings; whenObject.prototype.toString() is called on adefaultiterator object of a giveninterface, theclass string of theiterator prototype object of thatinterface is used.
3.6.9.5.Iterator prototype object
Theiterator prototype object for a giveninterface is an object that exists for every interface that has apair iterator. It serves as theprototype fordefault iterator objects for the interface.
The [[Prototype]]internal slot of aniterator prototype object must be%IteratorPrototype%.
Letresult be a value determined by the value ofkind:
- "
key" LetidlKey bepair’skey.
Letkey be the result ofconvertingidlKey to an ECMAScript value.
result iskey.
- "
value" LetidlValue bepair’svalue.
Letvalue be the result ofconvertingidlValue to an ECMAScript value.
result isvalue.
- "
key+value" LetidlKey bepair’skey.
LetidlValue bepair’svalue.
Letkey be the result ofconvertingidlKey to an ECMAScript value.
Letvalue be the result ofconvertingidlValue to an ECMAScript value.
Letarray be the result of performingArrayCreate(2).
CallCreateDataProperty(array, "
0",key).CallCreateDataProperty(array, "
1",value).result isarray.
- "
ReturnCreateIterResultObject(result,
false ).
Aniterator prototype object must have anext data property with attributes { [[Writable]]:
Letinterface be theinterface for which theiterator prototype object exists.
Letobject be the result of callingToObject on the
this value.Ifobjectis a platform object,thenperform a security check, passing:
the platform objectobject,
the identifier "
next", andthe type "
method".
Ifobject is not adefault iterator object forinterface,thenthrow a
TypeError.Letindex beobject’s index.
Letkind beobject’s kind.
Letvalues be the list ofvalue pairs to iterate over.
Letlen be the length ofvalues.
Ifindex is greater than or equal tolen, thenreturnCreateIterResultObject(
undefined ,true ).Letpair be the entry invalues at indexindex.
Setobject’s index toindex + 1.
Return theiterator result forpair andkind.
Theclass string of aniterator prototype object for a giveninterface is the result of concatenating theidentifier of theinterface and the string " Iterator".
3.6.9.6.Default asynchronous iterator objects
Adefault asynchronous iteratorobject for a giveninterface, target and iteration kind is an object whose [[Prototype]]internal slot is theasynchronous iterator prototype object for theinterface.
Adefault asynchronous iterator object has internal values:
itstarget, which is an object whosevalues are to be iterated,
itskind, which is the iteration kind,
itsongoing promise, which is a
Promiseor null,itsis finished, which is a boolean.
Note:Default asynchronous iterator objects do not haveclass strings; whenObject.prototype.toString() is called on adefault asynchronous iterator object of a giveninterface, theclass string of theasynchronous iterator prototype object of thatinterface is used.
3.6.9.7.Asynchronous iterator prototype object
Theasynchronous iterator prototype object for a giveninterface is an object that exists for every interface that has anasynchronously iterable declaration.It serves as the prototype fordefault asynchronous iterator objects for the interface.
The [[Prototype]]internal slot of anasynchronous iterator prototype object must be%AsyncIteratorPrototype%.
Anasynchronous iterator prototype object must have anext data property with attributes { [[Writable]]:
Letinterface be theinterface for which theasynchronous iterator prototype object exists.
LetthisValidationPromiseCapability be!NewPromiseCapability(
%Promise%).Letobject be the result of callingToObject on the
this value.IfAbruptRejectPromise(object,thisValidationPromiseCapability).
Ifobjectis a platform object, thenperform a security check, passing:
the platform objectobject,
the identifier "
next", andthe type "
method".
If this threw an exceptione, then:
Ifobject is not adefault asynchronous iterator object forinterface, then:
LetnextSteps be the following steps:
LetnextPromiseCapability be!NewPromiseCapability(
%Promise%).Ifobject’sis finished is true, then:
Letresult beCreateIterResultObject(
undefined ,true ).Perform!Call(nextPromiseCapability.[[Resolve]],
undefined , «result »).ReturnnextPromiseCapability.[[Promise]].
Letkind beobject’skind.
LetnextPromise be the result ofgetting the next iteration result withobject’starget andobject.
LetfulfillSteps be the following steps, givennext:
Setobject’songoing promise tonull.
Ifnext is
undefined , then:Setobject’sis finished to true.
Return!CreateIterResultObject(
undefined ,true ).
Otherwise:
Return theiterator result fornext andkind.
LetonFulfilled be!CreateBuiltinFunction(fulfillSteps, « »).
Perform!PerformPromiseThen(nextPromise,onFulfilled,
undefined ,nextPromiseCapability).ReturnnextPromiseCapability.[[Promise]].
Letpromise beobject’songoing promise.
Ifpromise is not null, then:
LetafterOngoingPromiseCapability be!NewPromiseCapability(
%Promise%).LetonFulfilled be!CreateBuiltinFunction(nextSteps, « »).
Perform!PerformPromiseThen(promise,onFulfilled,
undefined ,afterOngoingPromiseCapability).Setobject’songoing promise toafterOngoingPromiseCapability.[[Promise]].
Otherwise:
RunnextSteps and setobject’songoing promise to the result.
Returnobject’songoing promise.
If anasynchronous iterator return algorithm is defined for theinferface, then theasynchronous iterator prototype object must have areturn data property with attributes { [[Writable]]:
Letinterface be theinterface for which theasynchronous iterator prototype object exists.
LetreturnPromiseCapability be!NewPromiseCapability(
%Promise%).Letobject be the result of callingToObject on the
this value.IfAbruptRejectPromise(object,returnPromiseCapability).
Ifobjectis a platform object, thenperform a security check, passing:
the platform objectobject,
the identifier "
return", andthe type "
method".
If this threw an exceptione, then:
Ifobject is not adefault asynchronous iterator object forinterface, then:
Ifobject’songoing promise is not null, then:
Ifobject’sis finished is true, then:
Letresult be!CreateIterResultObject(value,
true ).Perform!Call(returnPromiseCapability.[[Resolve]],
undefined , «result »).ReturnreturnPromiseCapability.[[Promise]].
Setobject’sis finished to true.
LetreturnPromise be the result of running theasynchronous iterator return algorithmforinterface, givenobject’starget,object, andvalue.
LetfulfillSteps be the following steps:
Return!CreateIterResultObject(value,
true ).
LetonFulfilled be!CreateBuiltinFunction(fulfillSteps, « »).
Perform!PerformPromiseThen(returnPromise,onFulfilled,
undefined ,returnPromiseCapability).ReturnreturnPromiseCapability.[[Promise]].
Theclass string of anasynchronous iterator prototype object for a giveninterface isthe result of concatenating theidentifier of theinterface and the string" AsyncIterator".
3.6.10.Maplike declarations
Any object thatimplements aninterface that has amaplike declaration must have a [[BackingMap]]internal slot, which isinitially set to a newly createdMap object.ThisMap object’s [[MapData]] internal slot isthe object’smap entries.
If aninterfaceA is declared withamaplike declaration, thenthere exists a number of additional properties onA’sinterface prototype object.These additional properties are described in the sub-sections below.
Some of the properties below are defined to have afunction object value thatforwards to the internal map object for a given function name. Such functions behave as follows when invoked:
LetO be the
this value.Letarguments be the list of arguments passed to this function.
Letname be the function name.
IfOis a platform object,thenperform a security check, passing:
the platform objectO,
an identifier equal toname, and
the type "
method".
Letmap be the
Mapobject that is the value ofO’s [[BackingMap]]internal slot.
3.6.10.1.size
There must exist asize property onA’sinterface prototype object with the following characteristics:
The property has attributes{ [[Get]]:G, [[Enumerable]]:
false , [[Configurable]]:true },whereG is the interface’smap size getter,defined below.Themap size getter is abuilt-in function object whose behavior when invoked is as follows:
LetO be the
this value.IfOis a platform object,thenperform a security check, passing:
the platform objectO,
the identifier "
size", andthe type "
getter".
Letmap be the
Mapobject that is the value ofO’s [[BackingMap]]internal slot.ReturnGet(map, "
size").
The value of thefunction object’s
lengthproperty is the Number value0 .The value of thefunction object’s
nameproperty is the String value "size".
3.6.10.2.entries
Anentries data property must exist onA’sinterface prototype object with attributes { [[Writable]]:@@iterator property.
3.6.10.3.keys and values
For both ofkeys andvalues, there must exist a data property with that name onA’sinterface prototype object with the following characteristics:
The property has attributes { [[Writable]]:
true , [[Enumerable]]:false , [[Configurable]]:true }.The value of the property is abuilt-in function object thatforwards that name to the internal map object.
The value of thefunction objects’length properties is the Number value
The value of thefunction object’sname property is the String value "keys" or "values", correspondingly.
3.6.10.4.get and has
For both ofget andhas, there must exist a data property with that name onA’sinterface prototype object with the following characteristics:
The property has attributes{ [[Writable]]:
true , [[Enumerable]]:false , [[Configurable]]:true }.The value of the property is abuilt-in function object that behaves as follows when invoked:
LetO be the
this value.Letname be the name of the property – "
get" or "has".IfOis a platform object,thenperform a security check, passing:
the platform objectO,
an identifier equal toname, and
the type "
method".
Letmap be the
Mapobject that is the value ofO’s [[BackingMap]]internal slot.LetkeyType be the key type specified in themaplike declaration.
LetkeyArg be the first argument passed to this function, or
undefined if not supplied.LetkeyIDL be the result ofconvertingkeyArg to an IDL value of typekeyType.
Letkey be the result ofconvertingkeyIDL to an ECMAScript value.
The value of thefunction object’slength properties is the Number value
The value of thefunction object’sname property is the String value "get" or "has", correspondingly.
3.6.10.5.clear
IfA does not declare amember with identifier "clear", andA was declared with a read–write maplike declaration,then aclear data property with the following characteristicsmust exist onA’sinterface prototype object:
The property has attributes { [[Writable]]:
true , [[Enumerable]]:false , [[Configurable]]:true }.The value of the property is abuilt-in function object thatforwards
clearto the internal map object.
The value of thefunction object’slength property is the Number value
The value of thefunction object’sname property is the String value "clear".
3.6.10.6.delete
IfA does not declare amember with identifier "delete", andA was declared with a read–write maplike declaration,then adelete data property with the following characteristicsmust exist onA’sinterface prototype object:
The property has attributes { [[Writable]]:
true , [[Enumerable]]:false , [[Configurable]]:true }.The value of the property is abuilt-in function object that behaves as follows when invoked:
LetO be the
this value.IfOis a platform object,thenperform a security check, passing:
the platform objectO,
the identifier "
delete", andthe type "
method".
Letmap be the
Mapobject that is the value ofO’s [[BackingMap]]internal slot.LetkeyType be the key type specified in themaplike declaration.
LetkeyArg be the first argument passed to this function, or
undefined if not supplied.LetkeyIDL be the result ofconvertingkeyArg to an IDL value of typekeyType.
Letkey be the result ofconvertingkeyIDL to an ECMAScript value.
The value of thefunction object’slength property is the Number value
The value of thefunction object’sname property is the String value "delete".
3.6.10.7.set
IfA does not declare amember with identifier "set",andA was declared with a read–write maplike declaration,then aset data property with the following characteristicsmust exist onA’sinterface prototype object:
The property has attributes{ [[Writable]]:
true , [[Enumerable]]:false , [[Configurable]]:true }.The value of the property is abuilt-in function object that behaves as follows when invoked:
LetO be the
this value.IfOis a platform object,thenperform a security check, passing:
the platform objectO,
the identifier "
set", andthe type "
method".
Letmap be the
Mapobject that is the value ofO’s [[BackingMap]]internal slot.LetkeyType andvalueType be the key and value types specified in themaplike declaration.
LetkeyArg be the first argument passed to this function, or
undefined if not supplied.LetvalueArg be the second argument passed to this function, or
undefined if not supplied.LetkeyIDL be the result ofconvertingkeyArg to an IDL value of typekeyType.
LetvalueIDL be the result ofconvertingvalueArg to an IDL value of typevalueType.
Letkey be the result ofconvertingkeyIDL to an ECMAScript value.
Letvalue be the result ofconvertingvalueIDL to an ECMAScript value.
ReturnO.
The value of thefunction object’slength property is the Number value
The value of thefunction object’sname property is the String value "set".
3.6.11.Setlike declarations
Any object thatimplements aninterface that has asetlike declaration must have a [[BackingSet]]internal slot, which isinitially set to a newly createdSet object.ThisSet object’s [[SetData]] internal slot isthe object’sset entries.
If aninterfaceA is declared with asetlike declaration, thenthere exists a number of additional propertiesonA’sinterface prototype object.These additional properties are described in the sub-sections below.
Some of the properties below are defined to have abuilt-in function object value thatforwards to the internal set object for a given function name. Such functions behave as follows when invoked:
LetO be the
this value.Letarguments be the list of arguments passed to this function.
Letname be the function name.
IfOis a platform object,thenperform a security check, passing:
the platform objectO,
an identifier equal toname, and
the type "
method".
Letset be the
Setobject that isthe value ofO’s [[BackingSet]]internal slot.
3.6.11.1.size
Asize property must exist onA’sinterface prototype object with the following characteristics:
The property has attributes { [[Get]]:G, [[Enumerable]]:
false , [[Configurable]]:true },whereG is the interface’sset size getter,defined below.Theset size getter is abuilt-in function object whose behavior when invoked is as follows:
LetO be the
this value.IfOis a platform object,thenperform a security check, passing:
the platform objectO,
the identifier "
size", andthe type "
getter".
Letset be the
Setobject that is the value ofO’s [[BackingSet]]internal slot.Return the result of calling the [[Get]] internal method ofset passing "
size" andset as arguments.
The value of thefunction object’s
lengthproperty is the Number value0 .The value of thefunction object’s
nameproperty is the String value "size".
3.6.11.2.values
Avalues data property must exist onA’sinterface prototype object with attributes { [[Writable]]:@@iterator property.
3.6.11.3.entries and keys
For both ofentries andkeys, there must exist a data property with that name onA’sinterface prototype object with the following characteristics:
The property has attributes{ [[Writable]]:
true , [[Enumerable]]:false , [[Configurable]]:true }.The value of the property is abuilt-in function object thatforwards that name to the internal set object.
The value of thefunction object’slength properties isthe Number value
The value of thefunction object’sname property isthe String value "entries" or "keys", correspondingly.
3.6.11.4.has
There must exist ahas data property onA’sinterface prototype object with the following characteristics:
The property has attributes{ [[Writable]]:
true , [[Enumerable]]:false , [[Configurable]]:true }.The value of the property is abuilt-in function object that behaves as follows when invoked:
LetO be the
this value.IfOis a platform object,thenperform a security check, passing:
the platform objectO,
the identifier "
has", andthe type "
method".
Letset be the
Setobject that is the value ofO’s [[BackingSet]]internal slot.Lettype be the value type specified in thesetlike declaration.
Letarg be the first argument passed to this function, or
undefined if not supplied.LetidlValue be the result ofconvertingarg to an IDL value of typetype.
Letvalue be the result ofconvertingidlValue to an ECMAScript value.
The value of thefunction object’slength property is a Number value
The value of thefunction object’sname property is the String value "has".
3.6.11.5.add and delete
For both ofadd anddelete, if:
A does not declare anmember with a matching identifier, and
A was declared with a read–write setlike declaration,
then a data property with that name and the following characteristicsmust exist onA’sinterface prototype object:
The property has attributes { [[Writable]]:
true , [[Enumerable]]:false , [[Configurable]]:true }.The value of the property is abuilt-in function object that behaves as follows when invoked:
LetO be the
this value.Letname be the name of the property – "
add" or "delete".IfOis a platform object,thenperform a security check, passing:
the platform objectO,
an identifier equal toname, and
the type "
method".
Letset be the
Setobject that is the value ofO’s [[BackingSet]]internal slot.Lettype be the value type specified in thesetlike declaration.
Letarg be the first argument passed to this function, or
undefined if not supplied.LetidlValue be the result ofconvertingarg to an IDL value of typetype.
Letvalue be the result ofconvertingidlValue to an ECMAScript value.
Ifname is "delete", then returnresult.
Otherwise, returnO.
The value of thefunction object’slength property is the Number value
The value of thefunction object’sname property is the String value "add" or "delete", correspondingly.
3.6.11.6.clear
IfA does not declare amember with a matching identifier, andA was declared with a read–write setlike declaration,then aclear data property with the following characteristicsmust exist onA’sinterface prototype object:
The property has attributes { [[Writable]]:
true , [[Enumerable]]:false , [[Configurable]]:true }.The value of the property is abuilt-in function object thatforwards
clearto the internal map object.
The value of thefunction object’slength property is the Number value
The value of thefunction object’sname property is the String value "clear".
3.7.Platform objects implementing interfaces
Specifications may reference the concept "object implementsinterface" in various ways, including "object is aninterface object".
Everyplatform object is associated with aRealm, justas theinitial objects are.This Realm is stored in theplatform object's [[Realm]] slot.It is the responsibility of specifications using Web IDL to statewhich Realm (or, by proxy, which global object) each platformobject is associated with.In particular, the algorithms below associate the newplatform object withthe Realm given as an argument.
Return the result ofinternally creating a new object implementinginterface, withrealm and
undefined .
Assert:interface isexposed inrealm.
IfnewTarget is
undefined , then:Letprototype be theinterface prototype object forinterface inrealm.
Otherwise:
Assert:IsCallable(newTarget) is true.
IfType(prototype) is not Object, then:
LettargetRealm beGetFunctionRealm(newTarget).
Setprototype to theinterface prototype object forinterface intargetRealm.
Letslots be « [[Realm]], [[PrimaryInterface]] ».
Letinstance be a newly createdobject inrealm with an internal slot for each name inslots.
Setinstance.[[Realm]] torealm.
Setinstance.[[PrimaryInterface]] tointerface.
Setinstance.[[Prototype]] toprototype.
Setinstance’s essential internal methods to the definitions specified inECMA-262 Ordinary object internal methods and internal slots.
Letinterfaces be theinclusive inherited interfaces ofinterface.
For everyinterfaceancestor interface ininterfaces:
Letunforgeables be the value of the [[Unforgeables]] slot of theinterfaceobject ofancestor interface inrealm.
Letkeys be!unforgeables.[[OwnPropertyKeys]]().
For each elementkey ofkeys:
Letdescriptor be!unforgeables.[[GetOwnProperty]](key).
Perform!DefinePropertyOrThrow(instance,key,descriptor).
Ifinterface is declared with the [
Global]extended attribute, then:Define the regular operations ofinterface oninstance, givenrealm.
Define the regular attributes ofinterface oninstance, givenrealm.
Define the global property references oninstance, givenrealm.
Setinstance.[[SetPrototypeOf]] as defined in§ 3.7.1 [[SetPrototypeOf]].
Otherwise, ifinterfaces contains aninterface whichsupports indexed properties,named properties, or both:
Setinstance.[[GetOwnProperty]] as defined in§ 3.8.1 [[GetOwnProperty]].
Setinstance.[[Set]] as defined in§ 3.8.2 [[Set]].
Setinstance.[[DefineOwnProperty]] as defined in§ 3.8.3 [[DefineOwnProperty]].
Setinstance.[[Delete]] as defined in§ 3.8.4 [[Delete]].
Setinstance.[[PreventExtensions]] as defined in§ 3.8.5 [[PreventExtensions]].
Setinstance.[[OwnPropertyKeys]] as defined in§ 3.8.6 [[OwnPropertyKeys]].
Returninstance.
Letinterfaces be alist that contains everyinterface that isexposed inrealm.
Sortinterfaces in such a way that ifA andB areitems ofinterfaces,andAinherits fromB,A has a higher index ininterfaces thanB.
For everyinterface ofinterfaces:
Ifinterface is not declared with the [
NoInterfaceObject] or[LegacyNamespace]extended attributes, then:Letid beinterface’sidentifier.
LetinterfaceObject be the result ofcreatingan interface object forinterface withid inrealm.
Perform!CreateMethodProperty(target,id,interfaceObject).
If theinterface is declared with a [
LegacyWindowAlias]extended attribute,andtarget implements theWindowinterface, then:For everyidentifierid in[
LegacyWindowAlias]'sidentifiers:Perform!CreateMethodProperty(target,id,interfaceObject).
If theinterface is declared with a [
NamedConstructor]extended attribute,then:For everyidentifierid in[
NamedConstructor]'sidentifiers:LetnamedConstructor be the result ofcreatinga named constructor withid forinterface inrealm.
Perform!CreateMethodProperty(target,id,namedConstructor).
For everycallback interfaceinterface that isexposed inrealm and on whichconstants are defined:
Letid beinterface’sidentifier.
LetinterfaceObject be the result ofcreating a legacy callback interface object forinterface withid inrealm.
Perform!CreateMethodProperty(target,id,interfaceObject).
For everynamespacenamespace that isexposed inrealm:
Letid benamespace’sidentifier.
LetnamespaceObject be the result ofcreating a namespace object fornamespace inrealm.
Perform!CreateMethodProperty(target,id,namespaceObject).
Multipleplatform objects with differentglobal objects will share a reference to the sameinterface in their [[PrimaryInterface]] internal slots. For example, a page may contain a same-origin iframe, with the iframe’s method being called on the main page’s element of the same kind, with no exception thrown.
Interface mixins do not participate directly in the evaluation of theimplements algorithm. Instead, eachinterface that theinterface mixin isincluded in has its own "copy" of eachmember of theinterface mixin, and the correspondingoperation function checks that the receiverimplements the particularinterface whichincludes theinterface mixin.
TheRealm that a givenplatform object is associated with canchange after it has been created. WhentheRealm associated with a platform object is changed, its[[Prototype]]internal slot must be immediatelyupdated to be theinterface prototype object of theprimary interface from theplatform object’s newly associatedRealm.
Theclass string ofa platform object that implements one or more interfacesmust be thequalified name oftheprimary interface of the platform object.
Additionally,platform objects which implement aninterface which has a [Global]extended attribute get properties declaratively from:
Define those properties imperatively instead.
3.7.1.[[SetPrototypeOf]]
When the [[SetPrototypeOf]] internal method of aplatform objectO that implements aninterface with the [Global]extended attribute is called with ECMAScript language valueV, the following step is taken:
Return?SetImmutablePrototype(O,V).
Note: ForWindow objects, it is unobservable whether this is implemented, since the presence oftheWindowProxy object ensures that [[SetPrototypeOf]] is never called on aWindow objectdirectly. For other global objects, however, this is necessary.
3.8.Legacy platform objects
Legacy platform objects will appear to have additional properties that correspond to theirindexed andnamed properties. These properties are not “real” ownproperties on the object, but are made to look like they are by being exposedby the[[GetOwnProperty]] internal method .
It is permissible for an object to implement multiple interfaces that support indexed properties.However, if so, and there are conflicting definitions as to the object’ssupported property indices,then it is undefined what additional properties the object will appear tohave, or what its exact behavior will be with regard to its indexed properties.The same applies for named properties.
Theindexed property getter that is defined on the derived-most interface that thelegacy platform object implements is the one that defines the behaviorwhen indexing the object with anarray index. Similarly forindexed property setters.This way, the definitions of these special operations fromancestor interfaces can be overridden.
A property name is anunforgeable property name on agiven platform objectO if the object implements aninterface thathas aninterface member with that identifierand that interface member isunforgeable on any ofthe interfaces thatO implements.
Support forgetters is handled in§ 3.8.1 [[GetOwnProperty]],and forsetters in§ 3.8.3 [[DefineOwnProperty]] and§ 3.8.2 [[Set]].
Additionally,legacy platform objects have internal methods as defined in:
3.8.1.[[GetOwnProperty]]
The [[GetOwnProperty]] internal method of everylegacy platform objectO must behave as follows when called with property nameP:
ReturnLegacyPlatformObjectGetOwnProperty(O,P,
false ).
3.8.2.[[Set]]
The [[Set]] internal method of everylegacy platform objectO must behave as follows when called with property nameP, valueV, and ECMAScript language valueReceiver:
IfO andReceiver are the same object, then:
IfOimplements an interface with anindexed property setter andPis an array index, then:
Invoke the indexed property setter withP andV.
Return
true .
IfOimplements an interface with anamed property setter andType(P) is String, then:
Invoke the named property setter withP andV.
Return
true .
LetownDesc beLegacyPlatformObjectGetOwnProperty(O,P,
true ).Perform?OrdinarySetWithOwnDescriptor(O,P,V,Receiver,ownDesc).
3.8.3.[[DefineOwnProperty]]
When the [[DefineOwnProperty]] internal method of alegacy platform objectO is called with property keyP andProperty DescriptorDesc, the following steps must be taken:
IfOsupports indexed properties andPis an array index, then:
If the result of callingIsDataDescriptor(Desc) is
false , then returnfalse .IfO does not implement an interface with anindexed property setter, then return
false .Invoke the indexed property setter withP andDesc.[[Value]].
Return
true .
IfOsupports named properties,O does not implement aninterface with the [
Global]extended attribute,Type(P) is String,andP is not anunforgeable property name ofO, then:Letcreating be true ifP is not asupported property name, and false otherwise.
IfOimplements an interface with the [
OverrideBuiltins]extended attribute orO does not have an own propertynamedP, then:Ifcreating is false andO does not implement aninterface with anamed property setter, then return
false .IfOimplements an interface with anamed property setter, then:
If the result of callingIsDataDescriptor(Desc) is
false , then returnfalse .Invoke the named property setter withP andDesc.[[Value]].
Return
true .
IfO does not implement aninterface with the [
Global]extended attribute,then setDesc.[[Configurable]] totrue .ReturnOrdinaryDefineOwnProperty(O,P,Desc).
3.8.4.[[Delete]]
The [[Delete]] internal method of everylegacy platform objectO must behave as follows when called with property nameP.
IfOsupports indexed properties andPis an array index, then:
Letindex be the result of callingToUint32(P).
Ifindex is not asupported property index, then return
true .Return
false .
IfOsupports named properties,O does not implement aninterface with the [
Global]extended attribute and the result of calling thenamed property visibility algorithm with property nameP and objectO is true, then:IfO does not implement an interface with anamed property deleter, then return
false .Letoperation be the operation used to declare the named property deleter.
Ifoperation was defined without anidentifier, then:
Perform the steps listed in the interface description todelete an existing named property withP as the name.
If the steps indicated that the deletion failed, then return
false .
Otherwise,operation was defined with an identifier:
Perform the steps listed in the description ofoperation withP as the only argument value.
Ifoperation was declared with areturn type of
booleanand the steps returnedfalse , then returnfalse .
Return
true .
IfO has an own property with nameP, then:
If the property is not configurable, then return
false .Otherwise, remove the property fromO.
Return
true .
3.8.5.[[PreventExtensions]]
When the [[PreventExtensions]] internal method of alegacy platform object is called, the following steps are taken:
Return
false .
Note: this keepslegacy platform objects extensible by making [[PreventExtensions]] fail for them.
3.8.6.[[OwnPropertyKeys]]
This document does not define a complete property enumeration orderforplatform objects implementinginterfaces (or forplatform objects representing exceptions).However, it does forlegacy platform objects by defining the [[OwnPropertyKeys]]internal method as follows.
When the [[OwnPropertyKeys]] internal method of alegacy platform objectO is called, the following steps are taken:
Letkeys be a new emptylist of ECMAScript String and Symbol values.
IfOsupports indexed properties, thenfor eachindex ofO’ssupported property indices, in ascending numerical order,append!ToString(index) tokeys.
IfOsupports named properties, thenfor eachP ofO’ssupported property names that is visible according to thenamed property visibility algorithm,appendP tokeys.
For eachP ofO’s own property keys that is a String, in ascending chronological order ofproperty creation,appendP tokeys.
For eachP ofO’s own property keys that is a Symbol, in ascending chronological order ofproperty creation,appendP tokeys.
Assert:keys has no duplicate items.
Returnkeys.
3.8.7.Abstract operations
To determine if a property namePis anarray index, the following algorithm is applied:
IfType(P) is not String, then return
false .Letindex be!CanonicalNumericIndexString(P).
Ifindex is
undefined , then returnfalse .IfIsInteger(index) is
false ,then returnfalse .Ifindex is −0, then return
false .Ifindex < 0, then return
false .Ifindex ≥ 232 − 1, then return
false .Note: 232 − 1 is the maximum array length allowed by ECMAScript.
Return
true .
Thenamed property visibility algorithm is used to determine if a given named property is exposed on an object. Some named properties are not exposed on an object depending on whether the [OverrideBuiltins]extended attribute was used. The algorithm operates as follows, with property nameP and objectO:
IfP is not asupported property name ofO, then return false.
IfO has an own property namedP, then return false.
Note: This will include cases in whichO has unforgeable properties, because in practice those are always set up before objects have any supported property names, and once set up will make the corresponding named properties invisible.
IfOimplements an interface that has the [
OverrideBuiltins]extended attribute, then return true.Letprototype beO.[[GetPrototypeOf]]().
Whileprototype is not null:
Ifprototype is not anamed properties object,andprototype has an own property namedP, then return false.
Setprototype toprototype.[[GetPrototypeOf]]().
Return true.
This should ensure that for objects with named properties, property resolution is done in the following order:
Indexed properties.
Own properties, including unforgeable attributes and operations.
Then, if [
OverrideBuiltins]:Named properties.
Properties from the prototype chain.
Otherwise, if not [
OverrideBuiltins]:Properties from the prototype chain.
Named properties.
Toinvoke an indexed property setter with property nameP and ECMAScript valueV, the following steps must be performed:
Letindex be the result of callingToUint32(P).
Letcreating be true ifindex is not asupported property index,and false otherwise.
Letoperation be the operation used to declare the indexed property setter.
LetT be the type of the second argument ofoperation.
Letvalue be the result ofconvertingV to an IDL value of typeT.
Ifoperation was defined without anidentifier, then:
Ifcreating is true, then perform the steps listed in the interface description toset the value of a new indexed property withindex as the index andvalue as the value.
Otherwise,creating is false. Perform the steps listed in the interface description toset the value of an existing indexed property withindex as the index andvalue as the value.
Otherwise,operation was defined with an identifier. Perform the steps listed in the description ofoperation withindex andvalue as the two argument values.
Toinvoke a named property setter with property nameP and ECMAScript valueV, the following steps must be performed:
Letcreating be true ifP is not asupported property name, and false otherwise.
Letoperation be the operation used to declare the named property setter.
LetT be the type of the second argument ofoperation.
Letvalue be the result ofconvertingV to an IDL value of typeT.
Ifoperation was defined without anidentifier, then:
Ifcreating is true, then perform the steps listed in the interface description toset the value of a new named property withP as the name andvalue as the value.
Otherwise,creating is false. Perform the steps listed in the interface description toset the value of an existing named property withP as the name andvalue as the value.
Otherwise,operation was defined with an identifier. Perform the steps listed in the description ofoperation withP andvalue as the two argument values.
TheLegacyPlatformObjectGetOwnProperty abstract operation performs the following steps when called with an objectO, a property nameP, and a booleanignoreNamedProps value:
IfOsupports indexed properties andPis an array index, then:
Letindex be the result of callingToUint32(P).
Ifindex is asupported property index, then:
Letoperation be the operation used to declare the indexed property getter.
Letvalue be an uninitialized variable.
Ifoperation was defined without anidentifier, thensetvalue to the result of performing the steps listed in the interface description todetermine the value of an indexed property withindex as the index.
Otherwise,operation was defined with an identifier. Setvalue to the resultof performing the steps listed in the description ofoperation withindex as the only argument value.
Letdesc be a newly createdProperty Descriptor with no fields.
Setdesc.[[Value]] to the result ofconvertingvalue to an ECMAScript value.
IfOimplements an interface with anindexed property setter, then setdesc.[[Writable]] to
true , otherwise set it tofalse .Setdesc.[[Enumerable]] anddesc.[[Configurable]] to
true .Returndesc.
SetignoreNamedProps to true.
IfOsupports named properties andignoreNamedProps is false, then:
If the result of running thenamed property visibility algorithm withproperty nameP and objectO is true, then:
Letoperation be the operation used to declare the named property getter.
Letvalue be an uninitialized variable.
Ifoperation was defined without anidentifier, thensetvalue to the result of performing the steps listed in the interface description todetermine the value of a named property withP as the name.
Otherwise,operation was defined with an identifier. Setvalue to the resultof performing the steps listed in the description ofoperation withP as the only argument value.
Letdesc be a newly createdProperty Descriptor with no fields.
Setdesc.[[Value]] to the result ofconvertingvalue to an ECMAScript value.
IfOimplements an interface with anamed property setter, then setdesc.[[Writable]] to
true , otherwise set it tofalse .IfOimplements an interface with the[
LegacyUnenumerableNamedProperties]extended attribute,then setdesc.[[Enumerable]] tofalse ,otherwise set it totrue .Setdesc.[[Configurable]] to
true .Returndesc.
ReturnOrdinaryGetOwnProperty(O,P).
3.9.Callback interfaces
As described in§ 2.12 Objects implementing interfaces,callback interfaces can beimplemented in script by any ECMAScript object.The following cases explain how acallback interface'soperation is invoked on a givenobject:
If the object iscallable, then the implementation of the operation is thecallable object itself.
Otherwise, the implementation of the operation is calling the result of invoking theinternal [[Get]] method on the object with a property name that is theidentifier ofthe operation.
Note that ECMAScript objects need not haveproperties corresponding toconstants on them to be considered asimplementingcallback interfaces that happento have constants declared on them.
AWeb IDL arguments list is alist of values each of which is either an IDL value orthe special value “missing”, which represents a missing optional argument.
LetesArgs be an emptylist.
Leti be 0.
Letcount be 0.
Whilei <args’ssize:
Ifargs[i] is the special value “missing”, thenappend
undefined toesArgs.Otherwise,args[i] is an IDL value:
LetconvertResult be the result ofconvertingargs[i] to an ECMAScript value. Rethrow any exceptions.
AppendconvertResult toesArgs.
Setcount toi + 1.
Seti toi + 1.
TruncateesArgs to containcount items.
ReturnesArgs.
Tocall a user object’s operation, given acallback interface type valuevalue, operation nameopName,Web IDL arguments listargs, and optionalcallback this valuethisArg, perform the following steps. These steps will either return an IDL value or throw an exception.
Letcompletion be an uninitialized variable.
IfthisArg was not given, letthisArg be
undefined .LetO be the ECMAScript object corresponding tovalue.
Letrealm beO’sassociated Realm.
Letrelevant settings berealm’ssettings object.
Letstored settings bevalue’scallback context.
Prepare to run script withrelevant settings.
Prepare to run a callback withstored settings.
LetX beO.
If!IsCallable(O) is false, then:
LetgetResult beGet(O,opName).
IfgetResult is anabrupt completion, setcompletion togetResult and jump to the step labeledreturn.
SetX togetResult.[[Value]].
If!IsCallable(X) is
false ,then setcompletion to a newCompletion{[[Type]]: throw, [[Value]]: anewly createdTypeErrorobject, [[Target]]: empty}, and jumpto the step labeledreturn.SetthisArg toO (overriding the provided value).
LetesArgs be the result ofconvertingargs to an ECMAScriptarguments list. If this throws an exception, setcompletion to the completion valuerepresenting the thrown exception and jump to the step labeledreturn.
LetcallResult beCall(X,thisArg,esArgs).
IfcallResult is anabrupt completion, setcompletion tocallResult and jump to the step labeledreturn.
Setcompletion to the result ofconvertingcallResult.[[Value]] to an IDL value of the same type as the operation’sreturn type.
Return: at thispointcompletion will be set to an ECMAScript completion value.
Clean up after running a callback withstored settings.
Clean up after running script withrelevant settings.
Ifcompletion is a normal completion, returncompletion.
Ifcompletion is anabrupt completion and the operation has areturn type that isnot apromise type, returncompletion.
LetrejectedPromise be!Call(
%Promise_reject%,%Promise%, «completion.[[Value]]»).Return the result ofconvertingrejectedPromise to the operation’s return type.
3.9.1.Legacy callback interface object
For everycallback interface that isexposed ina givenRealm and on whichconstants are defined,a corresponding property exists on theRealm'sglobal object.The name of the property is theidentifier of thecallback interface,and its value is an object called thelegacy callback interface object.
Thelegacy callback interface object for a givencallback interface is abuilt-in function object.It has properties that correspond to theconstants defined on that interface,as described in sections§ 3.6.5 Constants.
Note: Since alegacy callback interface object is afunction object thetypeof operator will return "function"when applied to alegacy callback interface object.
Thelegacy callback interface object for a givencallback interfaceinterface withidentifierid and inRealmrealm iscreated as follows:
Letsteps be the following steps:
LetF be!CreateBuiltinFunction(steps, « »,realm).
Perform!SetFunctionName(F,id).
Perform!SetFunctionLength(F, 0).
Define the constants ofinterface onF givenrealm.
ReturnF.
3.10.Invoking callback functions
An ECMAScriptcallable object that is beingused as acallback function value iscalled in a manner similar to howoperations oncallback interface values are called (asdescribed in the previous section).
Toinvoke acallback function type valuecallable with aWeb IDL arguments listargs and an optionalcallback this valuethisArg, perform the following steps. These steps will either return an IDL value or throw an exception.
Letcompletion be an uninitialized variable.
IfthisArg was not given, letthisArg be
undefined .LetF be the ECMAScript object corresponding tocallable.
If!IsCallable(F) is
false :If the callback function’s return type is
void, return.Note: This is only possible when the callback function came from an attributemarked with [
TreatNonObjectAsNull].Return the result ofconverting
undefined to the callback function’s return type.
Letrealm beF’sassociated Realm.
Letrelevant settings berealm’ssettings object.
Letstored settings becallable’scallback context.
Prepare to run script withrelevant settings.
Prepare to run a callback withstored settings.
LetesArgs be the result ofconvertingargs to an ECMAScriptarguments list. If this throws an exception, setcompletion to the completion valuerepresenting the thrown exception and jump to the step labeledreturn.
LetcallResult beCall(F,thisArg,esArgs).
IfcallResult is anabrupt completion, setcompletion tocallResult and jump to the step labeledreturn.
Setcompletion to the result ofconvertingcallResult.[[Value]] to an IDL value of the same type as the operation’sreturn type.
Return: at thispointcompletion will be set to an ECMAScript completion value.
Clean up after running a callback withstored settings.
Clean up after running script withrelevant settings.
Ifcompletion is a normal completion, returncompletion.
Ifcompletion is anabrupt completion and the callback function has areturn type that isnot apromise type, returncompletion.
LetrejectedPromise be!Call(
%Promise_reject%,%Promise%, «completion.[[Value]]»).Return the result ofconvertingrejectedPromise to the callback function’s return type.
Some callback functions are instead used asconstructors. Such callback functions must not havea return type that is apromise type.
Toconstruct acallback function type valuecallable with aWeb IDL arguments listargs, perform the following steps. These steps will either return an IDL value or throw an exception.
Letcompletion be an uninitialized variable.
LetF be the ECMAScript object corresponding tocallable.
If!IsConstructor(F) is
false , throw aTypeErrorexception.Letrealm beF’sassociated Realm.
Letrelevant settings berealm’ssettings object.
Letstored settings becallable’scallback context.
Prepare to run script withrelevant settings.
Prepare to run a callback withstored settings.
LetesArgs be the result ofconvertingargs to an ECMAScriptarguments list. If this throws an exception, setcompletion to the completion valuerepresenting the thrown exception and jump to the step labeledreturn.
LetcallResult beConstruct(F,esArgs).
IfcallResult is anabrupt completion, setcompletion tocallResult and jump to the step labeledreturn.
Setcompletion to the result ofconvertingcallResult.[[Value]] to an IDL value of the same type as the operation’sreturn type.
Return: at thispointcompletion will be set to an ECMAScript completion value.
Clean up after running a callback withstored settings.
Clean up after running script withrelevant settings.
Returncompletion.
3.11.Namespaces
For everynamespace that isexposed in a givenRealm,a corresponding property exists on theRealm'sglobal object.The name of the property is theidentifier of the namespace, and its value is an objectcalled thenamespace object.
The characteristics of a namespace object are described in§ 3.11.1 Namespace object.
3.11.1.Namespace object
The namespace object for a givennamespacenamespace andRealmrealm iscreated as follows:
LetnamespaceObject be!ObjectCreate(realm.[[Intrinsics]].[[
%ObjectPrototype%]]).Define the regular attributes ofnamespace onnamespaceObject givenrealm.
Define the regular operations ofnamespace onnamespaceObject givenrealm.
For eachexposedinterfaceinterface which has the [
LegacyNamespace] extendedattribute with the identifier ofnamespace as its argument,Letid beinterface’sidentifier.
LetinterfaceObject be the result ofcreating aninterface object forinterface withid inrealm.
Perform!CreateMethodProperty(namespaceObject,id,interfaceObject).
ReturnnamespaceObject.
3.12.Exceptions
3.12.1.DOMException custom bindings
In the ECMAScript binding, theinterface prototype object forDOMException has its [[Prototype]]internal slot set to the intrinsic object%ErrorPrototype%,as defined in thecreate an interface prototype object abstract operation.
Additionally, if an implementation gives nativeError objects special powers ornonstandard properties (such as astack property),it should also expose those onDOMException instances.
3.12.2.Exception objects
Simple exceptions are representedby native ECMAScript objects of the corresponding type.
ADOMException is represented by aplatform object that implements theDOMException interface.
3.12.3.Creating and throwing exceptions
Tocreate asimple exception orDOMExceptionE, with a string giving theerror nameN for theDOMException case and optionally a string giving a user agent-defined messageM:
IfM was not specified, letM be
undefined .Letargs be a list of ECMAScript values determined based on the type ofE:
- E is
DOMException args is «M,N».
- E is asimple exception
args is «M».
- E is
LetX be an object determined based on the type ofE:
- E is
DOMException X is the
DOMExceptioninterface object from thecurrent Realm.- E is asimple exception
X is theconstructor for the corresponding ECMAScript errorfrom thecurrent Realm.
- E is
Tothrow asimple exception orDOMException, with a string giving theerror name for theDOMException case and optionally a string giving a user agent-defined message:
LetO be the result ofcreating an exception with the same arguments.
ThrowO.
The above algorithms restrictobjects representing exceptions propagating out of afunction object to be ones that are associated with theRealm of thatfunction object (i.e., thecurrent Realm at the time the function executes). For example, consider the IDL:
[Exposed =Window ]interface MathUtils { // If x is negative, throws a "NotSupportedError"DOMException.double computeSquareRoot (double x );};
If we applycomputeSquareRoot to aMathUtils object from a differentRealm, then the exception thrown will be from theRealm of the method, not the object it is applied to:
const myMU= window. getMathUtils(); // A MathUtils object from this Realm const otherMU= otherWindow. getMathUtils(); // A MathUtils object from a different Realm myMUinstanceof Object; // Evaluates to true. otherMUinstanceof Object; // Evaluates to false. otherMUinstanceof otherWindow. Object; // Evaluates to true. try { otherMU. doComputation. call( myMU, - 1 ); } catch ( e) { console. assert( ! ( einstanceof DOMException)); console. assert( einstanceof otherWindow. DOMException); }
3.12.4.Handling exceptions
Unless specified otherwise,whenever ECMAScript runtime semantics are invoked dueto requirements in this document andend due to an exception being thrown, that exceptionmust propagate to the caller, and ifnot caught there, to its caller, and so on.
PerDocument conventions, an algorithm specified in this document may intercept thrown exceptions, either by specifyingthe exact steps to take ifan exception was thrown, or by explicitly handlingabrupt completions.
The followingIDL fragment defines twointerfaces and anexception. ThevalueOf attribute onExceptionThrower is defined to throw an exception whenever an attempt is made to get its value.
[Exposed =Window ]interface Dahut {attribute DOMString type ;};[Exposed =Window ]interface ExceptionThrower { // This attribute always throws a NotSupportedError and never returns a value.attribute long valueOf ;};
Assuming an ECMAScript implementation supporting this interface, the following code demonstrates how exceptions are handled:
var d= getDahut(); // Obtain an instance of Dahut. var et= getExceptionThrower(); // Obtain an instance of ExceptionThrower. try { d. type= { toString: function () { throw "abc" ; } }; } catch ( e) { // The string "abc" is caught here, since as part of the conversion // from the native object to a string, the anonymous function // was invoked, and none of the [[DefaultValue]], ToPrimitive or // ToString algorithms are defined to catch the exception. } try { d. type= { toString: { } }; } catch ( e) { // An exception is caught here, since an attempt is made to invoke // [[Call]] on the native object that is the value of toString // property. } try { d. type= Symbol(); } catch ( e) { // An exception is caught here, since an attempt is made to invoke // the ECMAScript ToString abstract operation on a Symbol value. } d. type= et; // An uncaught "NotSupportedError" DOMException is thrown here, since the // [[DefaultValue]] algorithm attempts to get the value of the // "valueOf" property on the ExceptionThrower object. The exception // propagates out of this block of code.
3.13.Synthetic module records
ASynthetic Module Record is used to represent information about a module that isdefined by specifications.The set of exported names is static, and determined at creation time (as an argument toCreateSyntheticModule), while the set of exported values can be changed over time usingSetSyntheticModuleExport.It has no imports or dependencies.
Note: ASynthetic Module Record could be used for defining a variety of module types: forexample, built-in modules, or JSON modules, or CSS modules.
Note:Synthetic Module Records are being developed in concert with the authors of theJavaScript Standard Library proposal, and might eventually move to the ECMAScriptspecification.[JSSTDLIB][ECMA-262].
In addition to theModule Record Fields, Synthetic Module Records have the additional fieldslisted below.Each of these fields is initially set inCreateSyntheticModule.
| Field Name | Value Type | Meaning |
|---|---|---|
| [[ExportNames]] | List of String | A List of all names that are exported. |
| [[EvaluationSteps]] | An abstract operation | An abstract operation that will be performed upon evaluation of the module, taking theSynthetic Module Record as its sole argument. These will usually set up the exported values, by usingSetSyntheticModuleExport. They must not modify [[ExportNames]]. They may return an abrupt completion. |
3.13.1.CreateSyntheticModule
ReturnSynthetic Module Record { [[Realm]]:realm, [[Environment]]:
undefined , [[Namespace]]:undefined , [[HostDefined]]:hostDefined, [[ExportNames]]:exportNames, [[EvaluationSteps]]:evaluationSteps }.
Note: we could set up [[Environment]] either here or inLink().It is done inLink() for symmetry withSource Text Module Records,but there is no observable difference.
3.13.2.SetSyntheticModuleExport
LetenvRec bemodule.[[Environment]]'sEnvironmentRecord.
PerformenvRec.SetMutableBinding(exportName,exportValue,
true ).
3.13.3.Concrete Methods
The following are the concrete methods forSynthetic Module Record that implement thecorrespondingModule Record abstract methods.
3.13.3.1.GetExportedNames
It performs the following steps:
Letmodule be thisSynthetic Module Record.
Returnmodule.[[ExportNames]].
3.13.3.2.ResolveExport
It performs the following steps:
Letmodule be thisSynthetic Module Record.
Ifmodule.[[ExportNames]] does not containexportName, return
null .ReturnResolvedBinding Record { [[Module]]:module, [[BindingName]]:exportName }.
3.13.3.3.Link
It performs the following steps:
Letmodule be thisSynthetic Module Record.
Letrealm bemodule.[[Realm]].
Assert:realm is not
undefined .Letenv beNewModuleEnvironment(realm.[[GlobalEnv]]).
Setmodule.[[Environment]] toenv.
LetenvRec beenv’sEnvironmentRecord.
For eachexportName inmodule.[[ExportNames]],
Perform!envRec.CreateMutableBinding(exportName,
false ).Perform!envRec.InitializeBinding(exportName,
undefined ).
Return
undefined .
3.13.3.4.Evaluate
It performs the following steps:
Letmodule be thisSynthetic Module Record.
LetmoduleCxt be a newECMAScript code execution context.
Set theFunction ofmoduleCxt to
null .Assert:module.[[Realm]] is not
undefined .Set theRealm ofmoduleCxt tomodule.[[Realm]].
Set theScriptOrModule ofmoduleCxt tomodule.
Set theVariableEnvironment ofmoduleCxt tomodule.[[Environment]].
Set theLexicalEnvironment ofmoduleCxt tomodule.[[Environment]].
Suspend the currentlyrunning execution context.
PushmoduleCxt on to theexecution context stack;moduleCxt is now therunning execution context.
Letcompletion be the result of performingmodule.[[EvaluationSteps]](module).
SuspendmoduleCxt and remove it from theexecution context stack.
Resume the context that is now on the top of theexecution context stack as therunning execution context.
ReturnCompletion(completion).
4.Common definitions
This section specifies some common definitions that allconforming implementations must support.
4.1.ArrayBufferView
typedef (Int8Array or Int16Array or Int32Array or Uint8Array or Uint16Array or Uint32Array or Uint8ClampedArray or Float32Array or Float64Array or DataView )ArrayBufferView ;
TheArrayBufferView typedef is used to representobjects that provide a view on to anArrayBuffer.
4.2.BufferSource
typedef (ArrayBufferView or ArrayBuffer )BufferSource ;
TheBufferSource typedef is used to represent objectsthat are either themselves anArrayBuffer or whichprovide a view on to anArrayBuffer.
4.3.DOMException
TheDOMException type is aninterface type defined by the following IDLfragment:
[Exposed =(Window ,Worker ),Serializable ]interface DOMException { // but see below note about ECMAScript bindingconstructor (optional DOMString = "",message optional DOMString = "Error");name readonly attribute DOMString name ;readonly attribute DOMString message ;readonly attribute unsigned short code ;const unsigned short INDEX_SIZE_ERR = 1;const unsigned short DOMSTRING_SIZE_ERR = 2;const unsigned short HIERARCHY_REQUEST_ERR = 3;const unsigned short WRONG_DOCUMENT_ERR = 4;const unsigned short INVALID_CHARACTER_ERR = 5;const unsigned short NO_DATA_ALLOWED_ERR = 6;const unsigned short NO_MODIFICATION_ALLOWED_ERR = 7;const unsigned short NOT_FOUND_ERR = 8;const unsigned short NOT_SUPPORTED_ERR = 9;const unsigned short INUSE_ATTRIBUTE_ERR = 10;const unsigned short INVALID_STATE_ERR = 11;const unsigned short SYNTAX_ERR = 12;const unsigned short INVALID_MODIFICATION_ERR = 13;const unsigned short NAMESPACE_ERR = 14;const unsigned short INVALID_ACCESS_ERR = 15;const unsigned short VALIDATION_ERR = 16;const unsigned short TYPE_MISMATCH_ERR = 17;const unsigned short SECURITY_ERR = 18;const unsigned short NETWORK_ERR = 19;const unsigned short ABORT_ERR = 20;const unsigned short URL_MISMATCH_ERR = 21;const unsigned short QUOTA_EXCEEDED_ERR = 22;const unsigned short TIMEOUT_ERR = 23;const unsigned short INVALID_NODE_TYPE_ERR = 24;const unsigned short DATA_CLONE_ERR = 25;};
Note: as discussed in§ 3.12.1 DOMException custom bindings, the ECMAScript binding imposes additionalrequirements beyond the normal ones forinterface types.
EachDOMException object has an associatedname andmessage, bothJavaScript strings.
TheDOMException(message,name) constructor, when invoked, must run these steps:
Thename attribute’s getter must return thisDOMException object’sname.
Themessage attribute’s getter must return thisDOMException object’smessage.
Thecode attribute’s getter must return thelegacy code indicated in theerror names table for thisDOMException object’sname, or 0 if no such entry exists in the table.
DOMException objects areserializable objects.
Theirserialization steps, givenvalue andserialized, are:
- Setserialized.[[Name]] tovalue’sname.
- Setserialized.[[Message]] tovalue’smessage.
- User agents should attach a serialized representation of any interesting accompanying data which are not yet specified, notably the
stackproperty, toserialized.
Theirdeserialization steps, givenvalue andserialized, are:
- Setvalue’sname toserialized.[[Name]].
- Setvalue’smessage toserialized.[[Message]].
- If any other data is attached toserialized, then deserialize and attach it tovalue.
4.4.DOMTimeStamp
typedef unsigned long long DOMTimeStamp ;
TheDOMTimeStamp type is used for representinga number of milliseconds, either as an absolute time (relative to some epoch)or as a relative amount of time. Specifications that use this type will needto define how the number of milliseconds is to be interpreted.
4.5.Function
callback Function =any (any ...);arguments
TheFunctioncallback function type is used for representing function values with no restriction on what argumentsare passed to it or what kind of value is returned from it.
4.6.VoidFunction
callback VoidFunction =void ();
TheVoidFunctioncallback function type is used for representing function values that take no arguments and do notreturn any value.
5.Extensibility
This section is informative.
Extensions to language binding requirements can be specifiedusingextended attributes that do not conflict with those defined in this document. Extensions forprivate, project-specific use should not be included inIDL fragments appearing in other specifications. It is recommended that extensionsthat are required for use in other specifications be coordinatedwith the group responsible for work onWeb IDL, whichat the time of writing is theW3C Web Platform Working Group,for possible inclusion in a future version of this document.
Extensions to any other aspect of the IDL language arestrongly discouraged.
6.Legacy constructs
This section is informative.
Legacy WebIDL constructs exist only so thatlegacy Web platform features can be specified.They are generally prefixed with the "Legacy" string.It is strongly discouraged to use legacy WebIDL constructs in specificationsunless required to specify the behavior of legacy Web platform features,or for consistency with such features.Editors who wish to use legacy WebIDL constructs are strongly advised to discuss thisbyfiling an issue before proceeding.
Marking a construct as legacy does not, in itself,imply that it is about to be removed from this specification.It does suggest however, that it is a good candidatefor future removal from this specification,whenever various heuristics indicate thatthe Web platform features it helps specify can be removed altogetheror can be modified to rely on non-legacy WebIDL constructs instead.
7.Referencing this specification
This section is informative.
It is expected that other specifications that define Web platform interfacesusing one or moreIDL fragments will reference this specification. It is suggestedthat those specifications include a sentence such as the following,to indicate that the IDL is to be interpreted as described in thisspecification:
The IDL fragment in Appendix A of this specification must, in conjunction with the IDL fragments defined in this specification’s normative references, be interpreted as required forconforming sets of IDL fragments, as described in the “Web IDL” specification. [WEBIDL]
In addition, it is suggested that the conformance class for useragents in referencing specifications be linked to theconforming implementation class from this specification:
A conforming FooML user agent must also be aconforming implementation of the IDL fragment in Appendix A of this specification, as described in the “Web IDL” specification. [WEBIDL]
8.Privacy and Security Considerations
This specification defines a conversion layer between JavaScript and IDL values. An incorrectimplementation of this layer can lead to security issues.
This specification also provides the ability to use JavaScript values directly, through theany andobject IDL types. These values need to be handled carefully to avoid securityissues. In particular, user script can run in response to nearly any manipulation of these values,and invalidate the expectations of specifications or implementations using them.
This specification makes it possible to interact withSharedArrayBuffer objects, which can beused to build timing attacks. Specifications that use these objects need to consider such attacks.
9.Acknowledgements
This section is informative.
The editor would like to thank the following people for contributingto this specification:Glenn Adams,David Andersson,Jake Archibald,L. David Baron,Art Barstow,Nils Barth,Robin Berjon,David Bruant,Jan-Ivar Bruaroey,Marcos Cáceres,Giovanni Campagna,Domenic Denicola,Chris Dumez,Michael Dyck,Daniel Ehrenberg,Brendan Eich,João Eiras,Gorm Haug Eriksen,Sigbjorn Finne,David Flanagan,Aryeh Gregor,Dimitry Golubovsky,James Graham,Aryeh Gregor,Tiancheng “Timothy” Gu,Kartikaya Gupta,Marcin Hanclik,Jed Hartman,Stefan Haustein,Dominique Hazaël-Massieux,Ian Hickson,Björn Höhrmann,Kyle Huey,Lachlan Hunt,Oliver Hunt,Jim Jewett,Wolfgang Keller,Anne van Kesteren,Olav Junker Kjær,Takayoshi Kochi,Magnus Kristiansen,Takeshi Kurosawa,Yves Lafon,Travis Leithead,Jim Ley,Kevin Lindsey,Jens Lindström,Peter Linss,呂康豪 (Kang-Hao Lu),Kyle Machulis,Darien Maillet Valentine,Mark Miller,Ms2ger,Andrew Oakley,岡坂 史紀 (Shiki Okasaka),Jason Orendorff,Olli Pettay,Simon Pieters,Andrei Popescu,François Remy,Tim Renouf,Tim Ruffles,Alex Russell,Takashi Sakamoto,Doug Schepers,Jonas Sicking,Garrett Smith,Sam Sneddon,Jungkee Song,Josh Soref,Maciej Stachowiak,Anton Tayanovskyy,triple-underscore,Peter Van der Beken,Jeff Walden,Allen Wirfs-Brock,Jeffrey Yasskin and,Collin Xu.
Special thanks also go to Sam Weinig for maintaining this documentwhile the editor was unavailable to do so.
IDL grammar
This section defines an LL(1) grammar whose start symbol,
Each production in the grammar has on its right hand side either anon-zero sequence of terminal and non-terminal symbols, or anepsilon (ε) which indicates no symbols.Symbols that begin with an uppercase letter are non-terminal symbols.Symbols in monospaced fonts are terminal symbols.Symbols in sans-serif font that begin with a lowercase letter are terminalsymbols that are matched by the regular expressions (using Perl 5 regularexpression syntax[PERLRE]) as follows:
= | /-?([1-9][0-9]*|0[Xx][0-9A-Fa-f]+|0[0-7]*)/ | |
= | /-?(([0-9]+\.[0-9]*|[0-9]*\.[0-9]+)([Ee][+-]?[0-9]+)?|[0-9]+[Ee][+-]?[0-9]+)/ | |
= | /[_-]?[A-Za-z][0-9A-Z_a-z-]*/ | |
= | /"[^"]*"/ | |
= | /[\t\n\r ]+/ | |
= | /\/\/.*|\/\*(.|\n)*?\*\// | |
= | /[^\t\n\r 0-9A-Za-z]/ |
The tokenizer operates on a sequence of Unicode characters[UNICODE].When tokenizing, the longest possible match must be used. For example, if the inputtext is “a1”, it is tokenized as a singlelong",and “.” is tokenized as the quoted terminal symbol
The IDL syntax is case sensitive, both for the quoted terminal symbolsused in the grammar and the values used forA" is distinct from one named "a", and anextended attribute [namedconstructor] will not be recognized asthe [NamedConstructor]extended attribute.
Implicitly, any number of
The following LL(1) grammar, starting with
Definitions ::ExtendedAttributeList Definition Definitions εDefinition ::CallbackOrInterfaceOrMixin Namespace Partial Dictionary Enum Typedef IncludesStatement ArgumentNameKeyword ::async attribute callback const constructor deleter dictionary enum getter includes inherit interface iterable maplike mixin namespace partial readonly required setlike setter static stringifier typedef unrestricted CallbackOrInterfaceOrMixin ::callback CallbackRestOrInterface interface InterfaceOrMixin InterfaceOrMixin ::InterfaceRest MixinRest InterfaceRest ::identifier Inheritance { InterfaceMembers } ; Partial ::partial PartialDefinition PartialDefinition ::interface PartialInterfaceOrPartialMixin PartialDictionary Namespace PartialInterfaceOrPartialMixin ::PartialInterfaceRest MixinRest PartialInterfaceRest ::identifier { PartialInterfaceMembers } ; InterfaceMembers ::ExtendedAttributeList InterfaceMember InterfaceMembers εInterfaceMember ::PartialInterfaceMember Constructor PartialInterfaceMembers ::ExtendedAttributeList PartialInterfaceMember PartialInterfaceMembers εPartialInterfaceMember ::Const Operation Stringifier StaticMember Iterable AsyncIterable ReadOnlyMember ReadWriteAttribute ReadWriteMaplike ReadWriteSetlike Inheritance ::: identifier εMixinRest ::mixin identifier { MixinMembers } ; MixinMembers ::ExtendedAttributeList MixinMember MixinMembers εMixinMember ::Const RegularOperation Stringifier ReadOnly AttributeRest IncludesStatement ::identifier includes identifier ; CallbackRestOrInterface ::CallbackRest interface identifier { CallbackInterfaceMembers } ; CallbackInterfaceMembers ::ExtendedAttributeList CallbackInterfaceMember CallbackInterfaceMembers εCallbackInterfaceMember ::Const RegularOperation Const ::const ConstType identifier = ConstValue ; ConstValue ::BooleanLiteral FloatLiteral integer BooleanLiteral ::true false FloatLiteral ::decimal -Infinity Infinity NaN ConstType ::PrimitiveType identifier ReadOnlyMember ::readonly ReadOnlyMemberRest ReadOnlyMemberRest ::AttributeRest MaplikeRest SetlikeRest ReadWriteAttribute ::inherit AttributeRest AttributeRest AttributeRest ::attribute TypeWithExtendedAttributes AttributeName ; AttributeName ::AttributeNameKeyword identifier AttributeNameKeyword ::async required ReadOnly ::readonly εDefaultValue ::ConstValue string [ ] { } null Operation ::RegularOperation SpecialOperation RegularOperation ::ReturnType OperationRest SpecialOperation ::Special RegularOperation Special ::getter setter deleter OperationRest ::OptionalOperationName ( ArgumentList ) ; OptionalOperationName ::OperationName εOperationName ::OperationNameKeyword identifier OperationNameKeyword ::includes ArgumentList ::Argument Arguments εArguments ::, Argument Arguments εArgument ::ExtendedAttributeList ArgumentRest ArgumentRest ::optional TypeWithExtendedAttributes ArgumentName Default Type Ellipsis ArgumentName ArgumentName ::ArgumentNameKeyword identifier Ellipsis ::... εReturnType ::Type void Constructor ::constructor ( ArgumentList ) ; Stringifier ::stringifier StringifierRest StringifierRest ::ReadOnly AttributeRest RegularOperation ; StaticMember ::static StaticMemberRest StaticMemberRest ::ReadOnly AttributeRest RegularOperation Iterable ::iterable < TypeWithExtendedAttributes OptionalType > ; OptionalType ::, TypeWithExtendedAttributes εAsyncIterable ::async iterable < TypeWithExtendedAttributes , TypeWithExtendedAttributes > ; ReadWriteMaplike ::MaplikeRest MaplikeRest ::maplike < TypeWithExtendedAttributes , TypeWithExtendedAttributes > ; ReadWriteSetlike ::SetlikeRest SetlikeRest ::setlike < TypeWithExtendedAttributes > ; Namespace ::namespace identifier { NamespaceMembers } ; NamespaceMembers ::ExtendedAttributeList NamespaceMember NamespaceMembers εNamespaceMember ::RegularOperation readonly AttributeRest Dictionary ::dictionary identifier Inheritance { DictionaryMembers } ; DictionaryMembers ::DictionaryMember DictionaryMembers εDictionaryMember ::ExtendedAttributeList DictionaryMemberRest DictionaryMemberRest ::required TypeWithExtendedAttributes identifier ; Type identifier Default ; PartialDictionary ::dictionary identifier { DictionaryMembers } ; Default ::= DefaultValue εEnum ::enum identifier { EnumValueList } ; EnumValueList ::string EnumValueListComma EnumValueListComma ::, EnumValueListString εEnumValueListString ::string EnumValueListComma εCallbackRest ::identifier = ReturnType ( ArgumentList ) ; Typedef ::typedef TypeWithExtendedAttributes identifier ; Type ::SingleType UnionType Null TypeWithExtendedAttributes ::ExtendedAttributeList Type SingleType ::DistinguishableType any PromiseType UnionType ::( UnionMemberType or UnionMemberType UnionMemberTypes ) UnionMemberType ::ExtendedAttributeList DistinguishableType UnionType Null UnionMemberTypes ::or UnionMemberType UnionMemberTypes εDistinguishableType ::PrimitiveType Null StringType Null identifier Null sequence < TypeWithExtendedAttributes > Null object Null symbol Null BufferRelatedType Null FrozenArray < TypeWithExtendedAttributes > Null RecordType Null PrimitiveType ::UnsignedIntegerType UnrestrictedFloatType boolean byte octet UnrestrictedFloatType ::unrestricted FloatType FloatType FloatType ::float double UnsignedIntegerType ::unsigned IntegerType IntegerType IntegerType ::short long OptionalLong OptionalLong ::long εStringType ::ByteString DOMString USVString PromiseType ::Promise < ReturnType > RecordType ::record < StringType , TypeWithExtendedAttributes > Null ::? εBufferRelatedType ::ArrayBuffer DataView Int8Array Int16Array Int32Array Uint8Array Uint16Array Uint32Array Uint8ClampedArray Float32Array Float64Array ExtendedAttributeList ::[ ExtendedAttribute ExtendedAttributes ] εExtendedAttributes ::, ExtendedAttribute ExtendedAttributes εExtendedAttribute ::( ExtendedAttributeInner ) ExtendedAttributeRest [ ExtendedAttributeInner ] ExtendedAttributeRest { ExtendedAttributeInner } ExtendedAttributeRest Other ExtendedAttributeRest ExtendedAttributeRest ::ExtendedAttribute εExtendedAttributeInner ::( ExtendedAttributeInner ) ExtendedAttributeInner [ ExtendedAttributeInner ] ExtendedAttributeInner { ExtendedAttributeInner } ExtendedAttributeInner OtherOrComma ExtendedAttributeInner εOther ::integer decimal identifier string other - -Infinity . ... : ; < = > ? ByteString DOMString FrozenArray Infinity NaN Promise USVString any boolean byte double false float long null object octet or optional record sequence short symbol true unsigned void ArgumentNameKeyword BufferRelatedType OtherOrComma ::Other , IdentifierList ::identifier Identifiers Identifiers ::, identifier Identifiers εExtendedAttributeNoArgs ::identifier ExtendedAttributeArgList ::identifier ( ArgumentList ) ExtendedAttributeIdent ::identifier = identifier ExtendedAttributeIdentList ::identifier = ( IdentifierList ) ExtendedAttributeNamedArgList ::identifier = identifier ( ArgumentList )
Note: The
While the
Document conventions
The following typographic conventions are used in this document:
Defining instances of terms:example term
Links to terms defined in this document or elsewhere:example term
Grammar terminals:
sometoken Grammar non-terminals:
ExampleGrammarNonTerminal Grammar symbols:
identifier IDL types:
unsigned longECMAScript classes:
MapECMAScript language types: Object
Code snippets:
a = b + obj.f()Unicode characters:U+0030 DIGIT ZERO ("0")
Extended attributes: [
ExampleExtendedAttribute]Variable names in prose and algorithms:exampleVariableName.
IDL informal syntax examples:
[
extended_attributes ]interface identifier {/* interface_members... */};(Specific parts of the syntax discussed in surrounding prose arehighlighted.)
IDL grammar snippets:
ExampleGrammarNonTerminal ::OtherNonTerminal sometoken other AnotherNonTerminal ε //nothing Non-normative notes:
Note: This is a note.
Non-normative examples:
Normative warnings:
This is a warning.
Code blocks:
// This is an IDL code block.[
Exposed =Window ]interface Example {attribute long something ;};// This is an ECMAScript code block. window. onload= function () { window. alert( "loaded" ); };
The following conventions are used in the algorithms in this document:
Algorithms use theconventions of the ECMAScript specification,including the! and? notation for unwrappingCompletion Records.
Algorithms sometimes treat returning/throwing values and returningCompletion Records interchangeably. That is, an algorithm that uses return/throw terminology may be treated asreturning aCompletion Record, while one that returns aCompletion Record may be treated asreturning a value or throwing an exception. Similarly, to catch exceptions, defining thebehavior to adopt whenan exception was thrown and checking if theCompletion Record’s[[Type]] field is “throw” are equivalent.
Completion Records are extended by allowing them to contain values that are not ECMAScriptvalues, such as Web IDL values.
Conformance
Everything in this specification is normative except for diagrams,examples, notes and sections marked as being informative.
This specification depends on the Infra Standard.[INFRA]
The following conformance classes are defined by this specification:
- conforming set of IDL fragments
A set ofIDL fragments is consideredto be aconforming set of IDL fragments if, taken together, they satisfy all of themust-,required- and shall-levelcriteria in this specification that apply to IDL fragments.
- conforming implementation
A user agent is considered to be aconforming implementation relative to aconforming set of IDL fragments if it satisfies all of the must-,required- and shall-levelcriteria in this specification that apply to implementations for all languagebindings that the user agent supports.
- conforming ECMAScript implementation
A user agent is considered to be aconforming ECMAScript implementation relative to aconforming set of IDL fragments if it satisfies all of the must-,required- and shall-levelcriteria in this specification that apply to implementations for the ECMAScriptlanguage binding.



