6.3 Script Language Specification Overview


ECMA Script is an object-oriented programming language for performing computations and manipulating computational objects within a host environment. ECMA Script is not intended to be computationally self-sufficient; indeed, there are no standard provisions in ECMA Script for input of external data or output of computed results. Instead, it is expected that the computational environment of an ECMA Script program provides not only the objects and other facilities, but also certain environment-specific host objects, whose description and behavior are implementation dependent.

A scripting language is a programming language that is used to manipulate, customize, and automate the facilities of an existing system. In such systems, useful functionality is already available through a user interface, and the scripting language is a mechanism for exposing that functionality to program control. In this way, the existing system is said to provide a host environment of objects and facilities, which completes the capabilities of the scripting language. A scripting language is intended for use by both professional and nonprofessional programmers. To accommodate nonprofessional programmers, some aspects of the language may be somewhat less strict.

ECMA Script was originally designed to be a Web scripting language, providing a mechanism to enliven Web pages in browsers and to perform server computation as part of a Web-based client server architecture. Therefore, it is not surprising that some of the facilities of ECMA Script are similar to those used in other programming languages [JAVA], [C], [C++]. It can provide core scripting capabilities for a variety of host environments, and therefore the core scripting language is specified for ECMA Script to render it independent of any particular host environment.

A Web browser, also known by its technical name User Agent (UA), provides an ECMA Script host environment for client-side computation including, for instance, objects that represent windows , menus , pop-ups, dialog boxes, text areas, anchors, frames , history, cookies, and input/output. Further, the host environment provides a means to attach scripting code to events such as change of focus, page and image loading, unloading, error and abort, selection, form submission, and mouse actions. Scripting code appears within the HTML and the displayed page is a combination of user interface elements and fixed and computed text and images. The scripting code is reactive to user interaction and there is no need for a main program.

A Web server provides a different host environment for server-side computation including objects representing requests , clients , and files; and mechanisms to lock and share data. By using browser-side and server-side scripting together, it is possible to distribute computation between the client and server while providing a customized user interface for a Web-based application.

Each Web browser and server that supports ECMA Script supplies its own host environment, completing the ECMA Script execution environment.

6.3.1 Language

ECMA Script program is a cluster of communicating objects. An ECMA Script object is an unordered collection of properties, each with zero or more attributes that determine how each property can be used. For example, when the ReadOnly attribute for a property is set to true , any attempt by executed ECMA Script code to change the value of the property has no effect. Properties are containers that hold other objects, primitive values, or methods . A primitive value is a member of one of the following built-in types: Undefined , Null , Boolean , Number , and String ; an object is a member of the remaining built-in type Object ; and a method is a function associated with an object via a property.

ECMA Script defines a collection of built-in objects that round out the definition of ECMA Script entities. These built-in objects include the Global object, the Object object, the Function object, the Array object, the String object, the Boolean object, the Number object, the Math object, the Date object, the RegExp object, and the objects Error , EvalError , RangeError , ReferenceError , SyntaxError , TypeError , and URIError .

ECMA Script also defines a set of built-in operators that may not be, strictly speaking, functions or methods. ECMA Script operators include various unary operations, multiplicative operators, additive operators, bitwise shift operators, relational operators, equality operators, binary bitwise operators, binary logical operators, assignment operators, and the comma operator. ECMA Script syntax intentionally resembles Java syntax. ECMA Script syntax is relaxed to enable it to serve as an easy-to-use scripting language. For example, a variable is not required to have its type declared nor are types associated with properties, and defined functions are not required to have their declarations appear textually before calls to them.

6.3.2 Delegation-Based Inheritance

ECMA Script has a class model that is different from that of C++ or Java: instead of using class-based inheritance, it relies on delegation-based inheritance, which is more expressive and less structured. Objects are associated with constructors that create objects by allocating storage for the objects and assigning initial values to their properties. All constructors are associated with objects and are, essentially function objects themselves , but not all objects are required to have constructors. Objects are created by using constructors in new expressions; for example, new String("A String") creates a new String object. Invoking a constructor without using new has consequences that depend on the constructor. For example, String("A String") produces a primitive string, not an object.

Each constructor has a [[Prototype]] property that is used to implement delegation-based inheritance and shared properties. Every object created by that constructor has an implicit reference to the object's prototype associated with its constructor. Further, it is possible to have a delegation chain, known as a prototype chain, as every prototype may have an implicit reference to another prototype. When a reference is made to a property in an object, it is interpreted to refer to the first object in the delegation chain (or prototype chain) that contains a property of that name. In other words, first the object referenced directly is examined for such a property; if that object contains the named property, that is the property to which the reference refers; if that object does not contain the named property, the delegate, or prototype, for that object is examined next ; and so on.

Delegation based inheritance is more powerful and flexible than class-based inheritance. In a class-based object oriented language, in general, state is carried by instances, methods are carried by classes, and inheritance is only of structure and behavior. In ECMA Script, the state and methods are carried by objects, and structure, behavior, and state are all inherited. Unlike class-based object languages, properties can be added to objects dynamically by assigning values to them. That is, constructors are not required to name or assign values to all or any of the constructed object's properties. This significant increase in power requires careful control to avoid losing control and preventing a software engineering nightmare.

The following example illustrates some aspects of delegation-based inheritance. Consider creating a new object to serve as the base class. This requires (a) creating a constructor function whose name is the name of the new object, and subsequently, (b) creating an instance of the object by invoking the new operator followed by the function name and any parameters needed to initialize the object. The code in Example 6.2 creates a Viewer() function and then creates a Person object using the new command.

Example 6.2 Code for constructing an object.
  function Viewer(first, last) {   this.first = first;   this.last  = last;   }   var viewer = new Viewer("John", "Dough");   ...  

The new operator invokes the constructor passing in the parameters included with the new statement. A special variable, called this , exists within the scope of the constructor that points to the current object instance. Using this allows adding and modifying properties on the current object.

Once the object is constructed, there is a need to add methods for manipulating it. Example 6.3 illustrates how to create a toString() method to enable serializing the object. Creating the function constructs a global property whose name is the name of that function, namely Viewer.prototype.toString() . The first line of Example 6.3 is accessing the global Viewer property which is essentially the constructor.

Example 6.3 Code for constructing an object.
  Viewer.prototype.toString() {   return this.first + " " + this.last;   }  

Every object has a [[Prototype]] property, which makes Object Oriented Programming (OOP) possible in ECMA Script. When an object property is accessed, the interpreter searches for that property name in the list of the current object's properties. If the name does not exist there, then the interpreter looks at the [[Prototype]] property of the object to see if that object, the one pointed to by the [[Prototype]] property, has the named property. If there is no property there, then the interpreter looks to see if the [[Prototype]] property has a [[Prototype]] property. If it does not, then this process continues until either the property is found or until there are no more prototype properties to search.

To perform inheritance, consider indicating that a parent is a subclass of viewer. This can be achieved as illustrated in Example 6.4. Essentially, delegation is used to implement inheritance. The first line in this example sets up the prototype inheritance (i.e., delegation) chain. Whenever a property is performed within a Parent object, if it can't be found, then the interpreter works its way up the prototype chain. The Viewer object is the first in the chain because of line one. The constructor property is used in scripts to determine an object's type. Redefining the Parent 's prototype changes the constructor to Viewer . To nullify this side effect, the second line sets the constructor to Parent. The third line enables access to methods of a superclass that are hidden (i.e., not overwritten) by redefined methods in a subclass.

Example 6.4 Subclassing example.
  Parent.prototype = new Viewer();   Parent.prototype.constructor = Parent;   Parent.superclass = Viewer.prototype;   function Parent(first, last, gender) {   // initialize properties here   }  

Unfortunately, ECMA Script does not allow calling a superclass constructor method. The specific issue is the ability to invoke the Viewer' s constructor to set the first and last properties while the Parent constructor initializes the gender property only. As illustrated in Example 6.5, this need can be addressed by moving the initialization code into a new method and then calling that method from the subclass. The init() function is created only if some arguments are passed in; therefore, a call of the form new Viewer() cannot define that function. Similarly, a check in the Parent 's constructors causes it to initialize only when some arguments are passed in.

The inheritance (i.e., essentially delegation) chain is set-up by setting the [[Prototype]] property to the newly created object. For the purposes of inheritance, there is only a need to update its [[Prototype]] property and there is no need for the object to be initialized . It is assumed that the object instance is being used for inheritance when no properties are passed to its constructor.

When a new Viewer object is created, the Viewer constructor passes the two arguments to the object's init() method which then initializes the object properties. When a new Parent object is created, the Parent 's constructor attempts to invoke the object's init() method. Since no init method is defined for the Parent object, the interpreter starts crawling up the prototype chain. The next object in the chain is the Viewer object, so the Viewer 's init method is invoked to initialize the (superclass) object's properties. The last line of the Parent constructor initializes the gender property.

Example 6.5 Invoking the constructor of the superclass.
  function Viewer(first, last) {   if ( arguments.length > 0 ) this.init(first, last);   }   function Parent(first, last, gender) {   if ( arguments.length > 0 ) {   this.init(first, last);   this.gender = gender;   }   }  

What happens when there is a need to subclass the Parent object with, e.g., a Father object? The Viewer object needs to manage the first and last properties, the Parent object needs to manage the gender property, and the Father object needs to manage other properties. Following the pattern used earlier, to subclass Viewer requires that the Parent object creates an init() function that overwrites the init function of its superclass Viewer . When the init() method is invoked for the Parent object, the interpreter finds the init() method defined in the Parent and not the one defined for Viewer .

To prevent the interpreter from using the init method in the current object, there is a need to tell it to start looking at Viewer.prototype . This is achieved by defining the superclass class property, as illustrated in Example 6.6.

Example 6.6 Defining the superclass property.
  Parent.prototype = new Viewer();   Parent.prototype.constructor = Parent;   Parent.superclass = Viewer.prototype;   function Parent(first, last, id) {   if ( arguments.length > 0 ) this.init(first, last, id);   }   Parent.prototype.init = function(first, last, gender)   {   Parent.superclass.init(this, first, last);   this.gender = gender;   }  

6.3.3 Terms

A type is a set of data values. A primitive value is a member of one of the types Undefined , Null , Boolean , Number , or String . A primitive value is a datum that is represented directly at the lowest level of the script engine. The undefined value is a primitive value used when a variable has not been assigned a value. The type Undefined has exactly one value, called undefined. The null value is a primitive value that represents the null, empty, or non existent reference. The type Null has exactly one value, called null.

An object is a member of the type Object . It is an unordered collection of properties each of which contains a primitive value, object, or function. A function stored in a property of an object is called a method. A constructor is a Function object that creates and initializes objects. Each constructor has an associated prototype object that is used to implement inheritance and shared properties. A prototype is an object used to implement structure, state, and behavior inheritance in ECMA Script. When a constructor creates an object, that object implicitly references the constructor's associated prototype for the purpose of resolving property references. The constructor's associated prototype can be referenced by the program expression constructor.prototype , and properties added to an object's prototype are shared, through inheritance, by all objects sharing the prototype. A native object is any object supplied by an ECMA Script implementation independent of the host environment. Standard native objects are defined by the 3rd edition of the ECMA Script specification. Some native objects are built-in; others may be constructed during the course of execution of an ECMA Script program. A built-in object is any object supplied by a ECMA Script engine, independent of the host environment, which is present at the start of the execution of an ECMA Script program. Standard built-in objects are defined by the 3rd edition of the ECMA Script specification. Implementations may introduce additional nonstandard built-in objects. A host object is any object supplied by the host environment to complete the execution environment of ECMA Script. Any object that is not native is a host object.

A boolean value is a member of the type Boolean and is one of two unique values, true and false . The type Boolean represents a logical entity and consists of exactly two unique values. One is called true and the other is called false . A Boolean object is a member of the type Object and is an instance of the built-in Boolean object. That is, a Boolean object is created by using the Boolean constructor in a new expression, supplying a boolean as an argument. The resulting object has an implicit (unnamed) property that is the boolean. A Boolean object can be casted into a boolean value.

A string value is a member of the type String and is a finite ordered sequence of zero or more 16-bit unsigned integer values. Although each value usually represents a single 16-bit unit of UTF-16 text, the language does not place any restrictions or requirements on the values except that they be 16-bit unsigned integers. The type String is the set of all string values. A String object is a member of the type Object and is an instance of the built-in String object. That is, a String object is created by using the String constructor in a new expression, supplying a string as an argument. The resulting object has an implicit (unnamed) property that is the string. A String object can be coerced to a string value by calling the String constructor as a function.

A number value is a member of the type Number and is a direct representation of a number. The type Number is a set of values representing numbers . In ECMA Script, the set of values represents the double-precision 64-bit format IEEE 754 values [FLOAT] including the special Not-a-Number (NaN) values, positive infinity, and negative infinity. A Number object is a member of the type Object and is an instance of the built-in Number object. That is, a Number object is created by using the Number constructor in a new expression, supplying a number as an argument. The resulting object has an implicit (unnamed) property that is the number. A Number object can be coerced to a number value by calling the Number constructor as a function.

6.3.4 Encoding

ECMA Script source text is represented as a sequence of characters in the Unicode character encoding, version 2.1 or later, using the UTF-16 transformation format. The text is expected to have been normalized to Unicode Normalized Form C (canonical composition), as described in Unicode Technical Report 15. Conforming ECMA Script engine implementations are not required to perform any normalization of text or behave as though they were performing normalization of text themselves.

ECMA Script source text can contain any of the Unicode characters. All Unicode white space characters are treated as white space, and all Unicode line/paragraph separators are treated as line separators. Nonlatin Unicode characters are allowed in identifiers, string literals, regular expression literals, and comments. The phrase code point and the word character are used to refer to a 16-bit unsigned value representing a single unit of UTF-16 text. Unicode character refers to the abstract linguistic or typographical unit represented by a single Unicode scalar value (which may be longer than 16 bits and thus may be represented by more than one code point). This only refers to entities represented by single Unicode scalar values: the components of a combining character sequence are still individual Unicode characters , even though a user might think of the whole sequence as a single character.

In string literals, regular expression literals and identifiers, any character (code point) may also be expressed as a Unicode escape sequence consisting of six characters, namely \u plus four hexadecimal digits. Within a comment, such an escape sequence is effectively ignored as part of the comment. Within a string literal or regular expression literal, the Unicode escape sequence contributes one character to the value of the literal. Within an identifier, the escape sequence contributes one character to the identifier.

6.3.5 Types

A value is an entity that takes on one of nine types. There are nine types: Undefined , Null , Boolean , String , Number , Object , Reference , List , and Completion . Values of type Reference , List , and Completion are used only as intermediate results of expression evaluation and cannot be stored as properties of objects.

6.3.5.1 The String Type

The String type is the set of all finite ordered sequences of zero or more 16-bit unsigned integer values. The String type is generally used to represent textual data in a running ECMA Script program, in which case each element in the string is treated as a code point value. Each element is regarded as occupying a position within the sequence. These positions are indexed with nonnegative integers. The first element (if any) is at position 0, the next element (if any) at position 1, and so on. The length of a string is the number of elements (i.e., 16-bit values) within it. The empty string has length zero and therefore contains no elements.

When a string contains actual textual data, each element is considered to be a single UTF-16 unit. Whether or not this is the actual storage format of a String , the characters within a String are numbered as though they were represented using UTF-16. All operations on Strings (except as otherwise stated) treat them as sequences of undifferentiated 16-bit unsigned integers; they do not ensure the resulting string is in normalized form, nor do they ensure language-sensitive results.

The rationale behind these decisions was to keep the implementation of String as simple and high performing as possible. The intent is that textual data coming into the execution environment from outside (e.g., user input, text read from a file, or received over the network, etc.) be converted to Unicode Normalized Form C before the running program sees it. Usually this would occur at the same time incoming text is converted from its original character encoding to Unicode (and would impose no additional overhead). Since it is recommended that ECMA Script source code be in Normalized Form C, string literals are guaranteed to be normalized (if source text is guaranteed to be normalized), as long as they do not contain any Unicode escape sequences.

6.3.5.2 The Number Type

The Number type has 2 64 “2 53 +3 values, representing the double precision 64-bit format IEEE 754 values as specified in the IEEE Standard for Binary Floating-Point Arithmetic [FLOAT], except that the 2 53 “2 distinct NaN values of the IEEE Standard are represented in ECMA Script as a single special NaN value. The NaN value is produced by the program expression NaN, assuming that the globally defined variable NaN has not been altered by program execution. In some implementations, external code might be able to detect a difference between various NaN values, but such behavior is implementation-dependent; to ECMA Script code, all NaN values are indistinguishable from each other.

There are two other special values, called positive Infinity and negative Infinity. For brevity, these values are also referred to for expository purposes by the symbols + x and “ x, respectively. These two infinite number values are produced by the program expressions + Infinity (or simply Infinity) and Infinity, assuming that the globally defined variable Infinity has not been altered by program execution. The other 2 64 “2 53 values are called the finite numbers. Half of these are positive numbers and half are negative numbers; for every finite positive number there is a corresponding negative number having the same magnitude.

There is both a positive zero and a negative zero, also referred to by the symbols +0 and “0, respectively. The remaining 2 64 -2 53 -2 nonzero values are of two kinds:

  • Normalized : 2 64 “2 53 values having the form s x m x 2e where s is +1 or -1, m is a positive integer less than 2 53 but not less than 2 52 , and e is an integer ranging from “1074 to 971, inclusive.

  • Denormalized : The remaining 2 53 “2 values are de-normalized, having the form s x m x 2e where s is +1 or “1, m is a positive integer less than 2 52 , and e is “1074.

Some ECMA Script operators deal only with integers in the range “2 31 through 2 31 “1, inclusive, or in the range 0 through 2 32 “1, inclusive. These operators accept any value of the Number type but first convert each such value to one of 2 32 integer values. See the descriptions of the ToInt32 and ToUint32 operators.

6.3.5.3 Objects, Properties, and Attributes

An Object is an unordered collection of properties, each comprising a name, a value, and a set of attributes. A property can have zero or more attributes from the set specified in Table 6.1; in other words, each property is associated with a bit field in which a bit is set if and only if the corresponding attribute is present. The properties associated with an object could be regarded as the object's run time state. The attributes associated with a property can be regarded as the run-time metadata associated with that property.

Table 6.1. Attributes of an Objects Property

Attribute

Description

ReadOnly

The property is a read-only property. Attempts by ECMA Script code to write to the property is ignored. Note that in some cases the value of a property with the ReadOnly attribute may change over time because of actions taken by the host environment; therefore "ReadOnly" does not mean "constant and unchanging"!).

DontEnum

The property is not to be enumerated by a for-in enumeration.

DontDelete

Attempts to delete the property is ignored.

Internal

Internal properties have no name and are not directly accessible via the property accessor s . How these properties are accessed is implementation specific. How and when some of these properties are used is specified by the ECMA Script language specification.

Properties are either internal or noninternal. There are two types of access for normal (noninternal) properties: get and put, corresponding to retrieval and assignment, respectively. Internal properties and methods are not part of the language. They are defined purely for expository purposes. The names of internal properties are enclosed in double square brackets [[ ]]. Native ECMA Script objects have an internal property called [[Prototype]] . The value of this property is either null or an object and is used for implementing inheritance. Properties of the [[Prototype]] object are visible as properties of the child object for the purposes of get access, but not for put access. When an algorithm uses an internal property of an object and the object does not implement the indicated internal property, a TypeError exception is thrown.

Invocation of a function creates an execution context whose parameters are supplied by the caller as arguments to the function referenced by the [[Call]] property. An object may have a number of other internal method properties including [[Construct]] and [[Delete]] . Table 6.2 summarizes the internal properties used by ECMA Script and specifies, for each property, its behavior for native ECMA Script objects. Host objects may implement some or all of these internal methods with any implementation-dependent behavior.

Table 6.2. List of Internal Properties

Property

Parameters

Returns/Behavior

[[Prototype]]

 

The prototype of this object.

[[Class]]

 

A string value indicating the kind of this object.

[[Value]]

 

The internal state information for this object.

[[Get]]

(PropertyName)

The value of the property.

[[Put]]

(PropertyName,Value)

Sets the specified property to Value.

[[CanPut]]

(PropertyName)

A boolean indicating whether a [[Put]] succeeds.

[[HasProperty]]

(PropertyName)

A boolean indicating whether a property exists.

[[Delete]]

(PropertyName)

Removes the specified property from the object.

[[DefaultValue]]

(Hint)

The default primitive value for the object (not reference).

[[Construct]]

a list of argument values

Constructs an object; invoked via the new operator.

[[Call]]

a list of argument values

Executes code; invoked via a function call expression.

[[HasInstance]]

(Value)

A boolean indicating whether Value delegates behavior to this object.

[[Scope]]

 

A scope within which a Function object is executed.

[[Match]]

(String,Index)

A boolean resulting from a regular expression match test.

Objects that implement the [[Construct]] internal method are called constructors. Objects that implement the [[Call]] internal method are called functions. Of the native ECMA Script objects, only Function objects implement [[HasInstance]] . Every object (including host objects) implements the [[Prototype]] and [[Class]] properties and the [[Get]] , [[Put]] , [[CanPut]] , [[HasProperty]] , [[Delete]] , and [[DefaultValue]] methods. The [[DefaultValue]] method may, for some objects, simply throw a TypeError exception. The value of the [[Prototype]] property is either an object or null, and every [[Prototype]] chain has finite length (starting from any object, recursively accessing the [[Prototype]] property eventually leads to a null value). Whether or not a native object can have a host object as its [[Prototype]] depends on the implementation.

The value of the [[Class]] property is defined by the 3rd edition of the ECMA Script specification for every kind of built-in object. The value of the [[Class]] property of a host object may be any value, even a value used by a built-in object for its [[Class]] property. The value of a [[Class]] property is used internally to distinguish different kinds of built-in objects. Note that ECMA Script does not provide any standard means for a program to access that value except through Object.prototype.toString() .

6.3.5.4 Expected Behaviors

For a native object O, a string P and an object V, Tables 6.3 through 6.8 specify the steps taken when the methods [[Get]] , [[Put]] , [[CanPut]] , [[HasProperty]] , [[Delete]] and [[DefaultValue]] are called.

Table 6.3. Behavior of [[Get]] (P)

Step

Action

1

If O doesn't have a property with name P, go to step 4.

2

Get the value of the property.

3

Return Result of step 2.

4

If the [[Prototype]] of O is null, return undefined.

5

Call the [[Get]] method of [[Prototype]] with property name P.

6

Return Result of step 5.

Table 6.4. Behavior of [[Put]] (P,V)

Step

Action

1

Call the [[CanPut]] method of O with name P.

2

If the result of step 1 is false, then return.

3

If O doesn't have a property with name P, then go to step 6.

4

Set the value of P to V. The attributes of the property are not changed.

5

Return

6

Create a property with name P, set its value to V and give it empty attributes.

7

Return

Table 6.5. Behavior of [[CanPut]] (P)

Step

Action

1

If O doesn't have a property with name P, then go to step 4

2

If the property has the ReadOnly attribute, then return false.

3

Return true.

4

If the [[Prototype]] of O is null, then return true.

5

Call the [[CanPut]] method of [[Prototype]] of O with property name P.

6

Return result of step 5.

Table 6.6. Behavior of [[HasProperty]] (P)

Step

Action

1

If O has a property with name P, then return true.

2

If the [[Prototype]] of O is null, then return false.

3

Call the [[HasProperty]] method of [[Prototype]] with property name P

4

Return results of step 3.

Table 6.7. Behavior of [[Delete]] (P)

Step

Action

1

If O has a property with name P, return true.

2

If the property has the DontDelete attribute, return false.

3

Remove the property with name P from O and return true.

Table 6.8. Behavior of [[DefaultValue]] (hint)

Step

Action

1

If hint is a String or O is a Date Object, then go to step 2; otherwise, hint is either empty or a Number, then go to step 11.

2

Call the [[Get]] method of object O with argument toString .

3

If the result of step 2 is not an object, then go to step 6.

4

Call the [[Call]] method resulting from step 2 with O as the 'this' value and an empty argument list.

5

If the result of step 4 is a primitive value, then return that primitive.

6

Call the [[Get]] method of object O with argument valueOf .

7

If the result of step 6 is not an object, then go to step 19.

8

Call the [[Call]] method resulting from step 6 with O as the this value and an empty argument list.

9

If the result of step 8 is a primitive value, then return that primitive.

10

Go to step 19.

11

Call the [[Get]] method of object O with argument valueOf .

12

If the result of step 11 is not an object, then go to step 16.

13

Call the [[Call]] method resulting from step 11 with O as the 'this' value and an empty argument list.

14

If the result of step 13 is a primitive value, then return that primitive.

15

Call the [[Get]] method resulting from step 13 with argument toString.

16

If the result of step 5 is not an object, then go to step 19.

17

Call the [[Call]] method resulting from step 15 with O as the 'this' value and an empty argument list.

18

If the result of step 17 is a primitive value, then return that primitive.

19

Throw a TypeError exception.

When the [[DefaultValue]] method is called with no hint, it behaves as if the hint were Number, unless O is a Date object, in which case it behaves as if the hint were String. The implementation of [[DefaultValue]] for native objects can return only primitive values. If a host object implements its own [[DefaultValue]] method, it ensures that its [[DefaultValue]] method can return only primitive values.

6.3.5.5 The Reference Type

Variables in ECMA Script are variants. The use of Reference type is an internal type; it is not a language data type. A value of type Reference is used only as an intermediate result of expression evaluation and cannot be stored as the value of a variable or property.

The Reference type is to specify the late binding mechanism of a parameter passed to a function. It is also used to specify the behavior of such operators as delete , typeof , and the assignment operators. For example, the left-hand operand of an assignment is expected to produce a reference. The behavior of an assignment could, instead, be explained entirely in terms of a case analysis on the syntactic form of the left-hand operand of an assignment operator, except for one difficulty: Function calls are permitted to return references. This possibility is admitted purely for the sake of host objects. No standard built-in ECMA Script function returns a reference and there is no provision for a user-defined function to return a reference.

6.3.5.6 Abstract Operations

The two operations of GetValue() and PutValue() are implemented using two abstract operations: GetBase(V) returns the base object component of the reference V, and GetPropertyName(V) returns the property name component of the reference V. The logic associated with GetValue() and PutValue() is depicted in Tables 6.9 and 6.10.

Table 6.9. Behavior of GetValue (V)

Step

Action

1

If Type(V) is not Reference, return V.

2

Call GetBase(V).

3

If the result of step 2 is null, then throw a ReferenceError exception.

4

Call the [[Get]] method of the step 2 result, passing GetPropertyName(V) for the property name.

5

Return the result of step 4.

Table 6.10. Behavior of PutValue (V,W)

Step

Action

1

If Type(V) is not Reference, throw a ReferenceError exception.

2

Call GetBase(V).

3

If the result of step 2 is null, then go to step 6.

4

Call the [[Put]] method resulting from step 2, passing GetPropertyName(V) for the property name and W for the value.

5

Return

6

Call the [[Put]] method for the global object (see section 6.3.4), passing GetProperty-Name(V) for the property name and W for the value.

7

Return

6.3.5.7 Type Conversion

The ECMA Script run-time system performs automatic type conversion as needed. To clarify the semantics of certain constructs it is useful to define a set of conversion operators. These operators are not a part of the language; they are presented to enable description of the semantics of the language. The conversion operators are polymorphic; that is, they can accept a value of any standard type, but not of the internal types Reference , List , or Completion .

The operator ToPrimitive takes a Value argument and an optional argument PreferredType . The operator ToPrimitive converts its value argument to a non-Object type. If an object is capable of converting to more than one primitive type, it may use the optional hint PreferredType to favour that type.

No conversion is performed from primitive types to primitive types, namely the types of Undefined , Null , Boolean , Number , and String . Conversion of the Object type returns a default value for the Object . The default value is retrieved by calling the internal [[DefaultValue]] method of the object, passing the optional hint PreferredType . The behavior of the [[DefaultValue]] method is defined for all native objects.

The operators ToString , ToBoolean , ToNumber , and ToObject convert their argument to a value of type Boolean and Number according to Tables 6.11 through 6.14. Implementers of ECMA Script may find useful the paper and code for binary-to-decimal conversion of floating-point numbers at cm.bell-labs.com/cm/cs/doc/90/4-10.ps.gz [CONV], and cm.bell-labs.com/netlib/fp/dtoa.c.gz [CONV-CODE].

Table 6.11. Behavior of ToString

Input Type

Resulting String

Undefined

undefined

Null

null

Boolean

If the argument is true, then the result is "true".

If the argument is false, then the result is "false".

Number

The operator ToString converts a number m to string format as follows (for interpretation, see notes below):

Step 1.

If m is NaN, return the string "NaN".

Step 2.

If m is +0 or “0, return the string "0".

Step 3.

If m is less than zero, return the string concatenation of the string " “" and ToString(-m) .

Step 4.

If m is infinity, return the string "Infinity".

Step 5.

Otherwise, let n, k , and s be integers such that k >= 1, 10 k “1 <= s < 10 k , the number value for s x 10 n k is m , and k is as small as possible. Note that k is the number of digits in the decimal representation of s , that s is not divisible by 10, and that the least significant digit of s is not necessarily uniquely determined by these criteria.

Step 6.

If k = n = 21, return the string consisting of the k digits of the decimal representation of s (in order, with no leading zeroes), followed by n k occurrences of the character '0'.

Step 7.

If 0 < n = 21, return the string consisting of the most significant n digits of the decimal representation of s , followed by a decimal point '.', followed by the remaining k n digits of the decimal representation of s .

Step 8.

If “6 < n = 0, return the string consisting of the character '0', followed by a decimal point '.', followed by “ n occurrences of the character '0', followed by the k digits of the decimal representation of s .

Step 9.

Otherwise, if k = 1, return the string consisting of the single digit of s , followed by lowercase character 'e', followed by a plus sign '+' or minus sign ' “' according to whether n “1 is positive or negative, followed by the decimal representation of the integer abs( n “1) (with no leading zeros).

Step 10.

Return the string consisting of the most significant digit of the decimal representation of s , followed by a decimal point '.', followed by the remaining k “1 digits of the decimal representation of s , followed by the lowercase character 'e', followed by a plus sign '+' or minus sign '-' according to whether n -1 is positive or negative, followed by the decimal representation of the integer abs( n -1) with no leading zeros.

String

The input argument (no conversion)

Object

Apply the following steps:

Step 1 : Call ToPrimitive (input argument, hint String ) .

Step 2 : Call ToString (result of step 1 ) .

Step 3 : Return result of step 2.

Table 6.12. Behavior of ToBoolean

Input Type

Resulting Boolean

Undefined

false

Null

false

Boolean

The input argument (no conversion).

Number

The result is false if the argument is +0, “0, or NaN; otherwise the result is true.

String

The result is false if the argument is the empty string (its length is zero); otherwise the result is true.

Object

true

Table 6.13. Behavior of ToNumber

Input Type

Resulting Number

Undefined

NaN

Null

+0

Boolean

The result is false if the argument is +0, “0, or NaN; otherwise the result is true.

Number

The result equals the input argument (no conversion).

String

Applies a grammar to the input string to compute the number. If that grammar cannot interpret the string as an expansion of StringNumericLiteral, then the result of ToNumber is NaN.

Object

Applies the following steps:

  1. 1. Call ToPrimitive (input argument, hint Number ) .

  2. 2. Call ToNumber (result of step 1 ) .

  3. 3. Return the result of step 2.

Table 6.14. Behavior of ToObject

Input Type

Resulting Object

Undefined

Throw a TypeError exception.

Null

Throw a TypeError exception.

Boolean

Create a new Boolean object whose [[value]] property is set to the value of the boolean.

Number

Create a new Number object whose [[value]] property is set to the value of the number.

String

Create a new String object whose [[value]] property is set to the value of the string.

Object

The result is the input argument (no conversion).



ITV Handbook. Technologies and Standards
ITV Handbook: Technologies and Standards
ISBN: 0131003127
EAN: 2147483647
Year: 2003
Pages: 170

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net