24.11.2000
Aija Karppinen
Department of Computer Science
Helsinki
University of Technology
aija.karppinen@hut.fi
ECMAScript is a standard general purpose scripting language that was announced by the European Computer Manufacturers Association (ECMA). The language resolves the minor incompatibilities that have existed in scripting between various browser implementations. ECMAScript is an object oriented language for performing computations and manipulating computational objects within a host environment. It 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 but it can provide a core scripting capabilities for a variety of host environments. [6]
4.1 Objects
4.2 Comments
4.3 Tokens
4.4 Literals
4.5 Types
4.7 Expressions
4.8 Statements
4.10 Programs
4.11 Native ECMAScript Objects
Netscape developed JavaScript as a build-in client-side scripting to Navigator 2. After that, also Microsoft introduced its own scripting languages to Internet Explorer 3: VBScript, that was based on Microsoft's Visual Basic language, and JScript which was virtually 100% compatible with JavaScript.
To prevent possible incompatibilities in different browsers several companies (including Netscape and Microsoft) worked with a European computer standards group ECMA (European Computer Manufacturers Association). The development of the standard started in November 1996. The first standard was published in June 1997 and it was named politically neutral ECMAScript.
ECMA Standard was adopted by the ISO/IEC JTC 1 as ISO/IEC 16262 [5] in April 1998. The second edition of ECMAScript language specification ECMA-262 was released in June 1998 to keep the language fully aligned with ISO/IEC 16262. ECMAScript was essentially the version of JavaScript (1.1) found in Navigator 3. Navigator 4 and Internet Explorer 4 both implement this ECMA with some extensions.
3rd edition of ECMAScript released in December 1999 including powerful regular expressions, better string handling, new control statements, try/catch expection handling, tighter definition of errors, formatting for numeric output and minor changes in antipication of forthcoming internationalisation facilities and future language growth.
[2,4]Application independence is achieved because language is divided into two feature sets: a domain independent core (ECMAScript) and a domain specific object model (Document Object Model (DOM) from W3C for example). ECMAScript plus DOM is a modular reconstruction of client-side JavaScript available in modern browsers.
ECMAScript language specification defines a minimum criterias for scripting language and it is allowed to include extensions to the conforming implementation. These new extensions may then be added into the next edition of standard.
ECMAScript provides a core set of objects, including generic objects, functions, strings, numbers, booleans, dates and a utility math object. Real meat of object model is relegated outside the ECMAScript definition.
[2,4]Client Side:
A Web browser provides an ECMAScript host environment
for client-side computation including for example: objects representing windows,
menus, pop-ups, dialog boxes, text areas, anchors, frames, history, cookies, and
input/output. Also means to attach scripting code to events such as change of
focus, page and image loading, unloading, error, 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. Scripting code is reactive to user interaction There
are no needs for a main program.
Server side:
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.
Using scripting at both sides provides possibility to distribute computation between the client and server plus a customized user interface for a Web-based application. Each Web browser and server that supports ECMAScript supplies its own host environment, completing the ECMAScript execution environment.
[2]Basic language and host facilities are provided by objects, and an ECMAScript program is a cluster of communicating objects. An ECMAScript object is an unordered collection of properties each with zero or more attributes. Attributes determine how each property can be used - for example, when the ReadOnly attribute for a property is set to true , any attempt by executed ECMAScript 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.
ECMAScript defines a collection of built-in objects which round out the definition of ECMAScript entities.
ECMAScript also defines a set of built-in operators which may not be, strictly speaking, functions or methods. These are 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.
ECMAScript syntax intentionally resembles Java syntax. ECMAScript 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.
An object is a member of the type Object. It is an unordered collection of properties which contain primitive values, objects, or functions. A function stored in the property of an object is called a method.
ECMAScript contains not proper classes but supports
constructors that create objects by executing code that allocates
storage and do the initialization. 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.
All functions including constructors are objects, but not all objects are constructors. Each constructor has a Prototype property which is used to implement prototype-based inheritance and shared properties. Every object created by that constructor has an implicit reference to the prototype. All objects that do not directly contain a particular property that their prototype contains share that property and its value.
A prototype is an object used to implement structure, state, and behavior
inheritance in ECMAScript. 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.
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 ECMAScript, the state and methods are carried by objects, and structure, behavior, and state are all inherited.
A native object is any object supplied by an ECMAScript implementation independent of the host environment. Some native objects are built-in; others may be constructed during the course of execution of an ECMAScript program.
A built-in object is any object supplied by an ECMAScript implementation, independent of the host environment, that is present at the start of the execution of an ECMAScript program. Standard built-in objects are defined in ECMAScript language specification, but the ECMAScript implementation may specify and define others. Every built-in object is a native object.
A host object is any object supplied by the host environment to complete the execution environment of ECMAScript. Any object that is not native is a host object.
There are multiline and single line comments:
/*multiline comment*/
//singleline comment
ReservedWord: Keyword,FutureReservedWord, BooleanLiteral,
NullLiteral
Identifier
Punctuator
NumericLiteral
StringLiteral
There are following keywords:
break else new var typeof
case finally return void try
catch for switch while throw
continue function this with instanceof
default if delete in do
The following words are used as keywords in proposed extensions and are therefore reserved to allow for the possibility of future adoption of those extensions.
abstract enum int short boolean
export interface static byte extends
long super char final native
synchronized class float package throws
const goto private transient debugger
implements protected volatile double import
public
Punctuators are the following:
{ } ( ) [ ]
. ; , < > <=
>= == != === !== +
- * % ++ -- «
» >>> & | ^ !
~ && || ? : =
+= -= *= %= «= »=
>>>= &= |= ^=
DivPunctuator is one of
/ /=
A type is a set of data values. In general, the correct functioning of a program is not affected if different data values of the same type are substituted for others. There are nine types (Undefined, NULL, Boolean, String, Number, Object, Reference, List and Completion).
The type Undefined has exactly one value, called undefined.
The type Null has exactly one value, called null.
The type Boolean represents a logical entity and consists of exactly two unique values. One is called true and the other is called false.
The type String is the set of all finite ordered sequences of zero or more Unicode characters.
The type Number is a set of values representing numbers. In ECMAScript the set of values represent the double-precision 64-bit format IEEE 754 value along with a special "Not-a-Number" (NaN) value, positive infinity, and negative infinity.
An Object is an unordered collection of properties. Each property consists of a name, a value and a set of attributes. Attributes can be: ReadOnly, DontEnum, DontDelete and Internal.
The internal Reference type is not a language data type. A value of type Reference is used only as an intermediate result of expression evaluation. A Reference is a reference to a property of an object.
The internal List type is not a language data type. The
List type is used to explain the evaluation of argument lists in
new expressions and in function calls. Values of the
List type are simply ordered sequences of values.
The internal Completion type is not a language data type. The Completion type is used to explain the behaviour of statements (break,continue,returnandthrow) that perform nonlocal transfers of control.
When control is transferred to ECMAScript code, control is entering an execution context. Active execution contexts logically form a stack. The top execution context on this logical stack is the running execution context. Every function and constructor call enters a new execution context and every return exits an execution context.
Every execution context has associated with it a scope chain, a
this value and a variable object. A scope chain is a list of
objects that are searched when evaluating an Identifier. The
this value depends on the caller and the type of code being
executed. Variables and functions declared in the source text are added as
properties of the variable object. For function code, parameters are added as
properties of the variable object.
When control enters an execution context, the scope chain is created and
initialised, variable instantion is performed and the this
value is determined.
this
Identifier
Literal
ArrayLiteral
ObjectLiteral
{ Expression}
NewExpression
CallExpression
LeftHandSideExpression
LeftHandSideExpression ++
LeftHandSideExpression --
PostfixExpressiondeleteUnaryExpressionvoidUnaryExpressiontypeofUnaryExpression++UnaryExpression--UnaryExpression+UnaryExpression-UnaryExpression~UnaryExpression!UnaryExpression
UnaryExpression
MultiplicativeExpression * UnaryExpression
MultiplicativeExpression / UnaryExpression
MultiplicativeExpression % UnaryExpression
MultiplicativeExpression
AdditiveExpression + MultiplicativeExpression
AdditiveExpression - MultiplicativeExpression
AdditiveExpression
ShiftExpression « AdditiveExpression
ShiftExpression » AdditiveExpression
ShiftExpression >>> AdditiveExpression
ShiftExpressionNoIn variants are needed to avoid confusing the
RelationalExpression < ShiftExpression
RelationalExpression > ShiftExpression
RelationalExpression <= ShiftExpression
RelationalExpression >= ShiftExpression
RelationalExpressioninstanceofShiftExpression
RelationalExpressioninShiftExpression
in in a relational expression with the
in operator in a for statement.
ShiftExpression
RelationalExpressionNoIn < ShiftExpression
RelationalExpressionNoIn > ShiftExpression
RelationalExpressionNoIn <= ShiftExpression
RelationalExpressionNoIn >= ShiftExpression
RelationalExpressionNoIninstanceofShiftExpression
RelationalExpressionEqualityExpressionNoIn:
EqualityExpression == RelationalExpression
EqualityExpression != RelationalExpression
EqualityExpression === RelationalExpression
EqualityExpression !== RelationalExpression
RelationalExpressionNoIn
EqualityExpressionNoIn == RelationalExpressionNoIn
EqualityExpressionNoIn != RelationalExpressionNoIn
EqualityExpressionNoIn === RelationalExpressionNoIn
EqualityExpressionNoIn !== RelationalExpressionNoIn
EqualityExpressionBitwiseANDExpressionNoIn:
BitwiseANDExpression & EqualityExpression
EqualityExpressionNoInBitwiseXORExpression:
BitwiseANDExpressionNoIn & EqualityExpressionNoIn
BitwiseANDExpressionBitwiseXORExpressionNoIn:
BitwiseXORExpression ^ BitwiseANDExpression
BitwiseANDExpressionNoInBitwiseORExpression:
BitwiseXORExpressionNoIn ^ BitwiseANDExpressionNoIn
BitwiseXORExpressionBitwiseORExpressionNoIn:
BitwiseORExpression | BitwiseXORExpression
BitwiseXORExpressionNoIn
BitwiseORExpressionNoIn | BitwiseXORExpressionNoIn
BitwiseORExpressionLogicalANDExpressionNoIn:
LogicalANDExpression && BitwiseORExpression
BitwiseORExpressionNoInLogicalORExpression:
LogicalANDExpressionNoIn && BitwiseORExpressionNoIn
LogicalANDExpressionLogicalORExpressionNoIn:
LogicalORExpression || LogicalANDExpression
LogicalANDExpressionNoIn
LogicalORExpressionNoIn || LogicalANDExpressionNoIn
LogicalORExpressionConditionalExpressionNoIn:
LogicalORExpression ? AssigmentExpression : AssigmentExpression
LogicalORExpressionNoIn
LogicalORExpressionNoIn ? AssigmentExpression : AssigmentExpressionNoIn
ConditionalExpressionAssignmentExpressionNoIn:
LeftHandSideExpression AssignmentOperator AssignmentExpression
ConditionalExpressionNoInAssignmentOperator: on of
LeftHandSideExpression AssignmentOperator AssignmentExpressionNoIn
= *= /= %= += -= <<= >>=
>>>= &= ^= |=
AssignmentExpressionExpressionNoIn:
Expression , AssignmentExpression
AssignmentExpressionNoIn
ExpressionNoIn , AssignmentExpressionNoIn
{ StatementList }
var
VariableDeclarationList;
;
Expression;
if( Expression ) StatementelseStatement
if ( Expression )
Statement
doStatementwhile( Expression );
while ( Expression ) Statement
for ( ExpressionNoIn ;
Expression ; Expression ) Statement
for(varVariableDeclarationListNoIn ; Expression ; Expression ) Statement
for( LeftHandSideExpresssioninExpression ) Statement
for(varVariableDeclarationListNoIninExpression ) Statement
continue Identifier;
break Identifier;
return Expression;
with ( Expression )
Statement
switch ( Expression )
CaseBlock
Identifier : Statement
throw Expression;
tryBlockcatch( Identifier ) Block
tryBlockcatch( Identifier ) BlockfinallyBlock
tryBlockfinallyBlock
Program consists of source elements which are Statements or FunctionDeclarations.
A native object is any object supplied by an ECMAScript implementation independent of the host environment. Some native objects are built-in; others may be constructed during the course of execution of an ECMAScript program.
A built-in object is any object supplied by an ECMAScript implementation, independent of the host environment, that is present at the start of the execution of an ECMAScript program. Standard built-in objects are defined in ECMAScript language specification, but the ECMAScript implementation may specify and define others. Every built-in object is a native object.
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 Error objects Error, EvalError, RangeError, ReferenceError, SyntaxError, TypeError and URIError.
Global object is the scope of the executing programs. Others are accessible as initial properties of the global object. Many build-in objects are functions: they can be invoked with arguments. Some of them furthermore are constructors: they are functions intended for use with the new operator.
Global Object is the scope of executing programs. It is not
possible to use the global object as a constructor with the
new operator.
Object object is created by callingObjectconstructor in anewexpression.
The function callFunction(...)is equivalent to the object creation expressionnew Function(...)with the same arguments: both creates and initialises a new Function object.
Array objects give special treatment to a certain class of property names. The function callArray(...)is equivalent to the object creation expressionnew Expression(...)with the same arguments: both creates and initialises a new Array object.
A string object is created by using theStringconstructor in anewexpression, supplying a string as an argument. The resulting object has an implicit (unnamed) property which is the string. A string object can be coerced to a string value. WhenStringis called as a function, it performs a type conversion.
A boolean object is created by using theBooleanconstructor in anewexpression, supplying a boolean as an argument. The resulting object has an implicit (unnamed) property which is the boolean. A boolean object can be coerced to a boolean value. WhenBooleanis called as a function, it performs a type conversion.
A number object is created by using theNumberconstructor in anewexpression, supplying a number as an argument. The resulting object has an implicit (unnamed) property which is the number. A number object can be coerced to a number value. WhenNumberis called as a function, it performs a type conversion. Note that a number object can have shared properties by adding them to the Number prototype.
The Math object is a single object that has some named properties, some of which are functions. It is not possible to use the Math object as as constructor with thenewoperator. There are for example the following functions:abs(x), exp(x) and log(x).
A Date object contains a number indicating a particular instant in time to within a millisecond. WhenDateis called as a function rather than as a constructor, it returns a string represating the current time. WhenDateis called as part of anewexpression, it is a constructor: it initialises the newly created object.
A RegExp object contains a regular expression and the associated flags. WhenRegExpis called as part of anewexpression, it is a constructor: it initializes the newly created object.
Instances of Error objects are thown as exceptions when runtime
errors occur. The Error objects may also serve as base for user-defined
exception classes. Error objects are created by new
expressions. ECMAScript is useful for example with the following languages in addition to HTML:
The XML Style Language (XSL) will allow the ECMAScript derivate of JavaScript to be used to evaluate and process the contents of XML elements prior to displaying them either as HTML elements or using the display object types defined in ISO's Document Style Semantics and Specification Language (DSSL). The XSL was co-submitted to the W3C by Microsoft, Inso Corporation and ArborText in August 1997. [3]
ECMAScript can be used with ISO/IEC 14772 (Virtual Reality Modeling Language , VRML) to provide scripting of events, objects and actions. ECMAScript enables VRML Script nodes to interact with VRML scenes.
url field of the Script node may contain URL references to ECMAScript code as illustrated below:Script { url "http://foo.com/myScript.js"}
The javascript allows the script to be placed inline as follows:Script { url "javascript: function foo () { ... }" }
[8]
To get a better touch of what the ECMAScript looks like, the next chapter gives some simple examples of JavaScript, ie. an implementation of ECMAScript Language specification.
Netscape JavaScript, also called client side JavaScript (CSJS) allows a client browser to display HTML and execute JavaScript code resulting in a page that the user sees. JavaScript statements embedded in an HTML page can respond to user events such as mouse-clicks, form input, and page navigation.
LiveWire JavaScript, also called server side JavaScript (SSJS) is an application development environment that uses JavaScript for creating server based applications similar to CGI programs.
Any Javascript code that does not write out to the document should be placed within the head of the document. This ensures that the JavaScript function definitions have been loaded by the browser before it is required. It also makes it easier to maintain the code if it can always be found in the head of the document.
There is a simple JavaScript example below which makes a button and when you press it a text "Hello World" becomes visible.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"
"http://www.w3.org/TR/REC-html40/loose.dtd">
<HTML>
<HEAD>
<SCRIPT LANGUAGE="JavaScript">
<!--
function functionName() {
alert(text);
}
var text = 'Hello World';
//-->
</SCRIPT>
</HEAD>
<BODY>
<SCRIPT LANGUAGE="JavaScript">
<!--
document.write('<FORM>' +
'<INPUT TYPE="BUTTON" VALUE="Click Here" ' +
'onClick="functionName()"></FORM>');
//-->
</SCRIPT>
</BODY>
</HTML>
|
Here are some other examples of JavaScript and some other possible places to put the JavaScript code.
Event Handlers:
This example prints "Hello World" when clicking the link "text link". Then it goes to the page.htm.
<A HREF="page.htm" onClick="alert('Hello World')">text link<
/A>
|
Links:
This example prints "Hello World" when clicking the link "text link".
<A HREF="javascript:alert('Hello world')">text link</A>
|
Source files:
The code below runs the script from the file library.js.
<SCRIPT SRC="library.js"></SCRIPT> |
It is important to specify some common rules of scripting to prevent incompatibilities between different scripting languages. A conforming implementation must provide and support all the types, values, objects, properties, functions and program syntax and semantics described in the ECMAScript language specification. It may however provide additional features and support program and regular expression syntax not described in the language specification. It is permitted also to support program syntax that makes use of the "future reserved words" listed in the specification.
Work on the language is not complete. The technical committee is working on significant enchancements, including mechanisms for scripts to be created and used across the Internet, and tighter coordination with other standards bodies such as groups within World Wide Web Consortium and the Wireless Application Protocol Forum.
[2]| [1] | Dyer, J., What is ECMAScript?, 1998, [viitattu 3.11.2000] < http://webreview.com/wr/pub/98/09/11/feature/sidebar1.html > |
| [2] | ECMA General Assembly, ECMAScript Language Specification (ECMA-262),
December 1999, 3rd, [viitattu 3.11.2000] < http://www.ecma.ch/ecma1/STAND/ECMA-262.HTM > |
| [3] | ETHOS, Technology Briefings Series 1:Developments Shaping Internets
and Intranets, The Extensible Markup Language (XML), 4.2.1998, [viitattu
3.11.2000] < http://www.personal.u-net.com/~sgml/xml.htm > |
| [4] | Goodman, D., ECMAScript, 1998, [viitattu 3.11.2000] < http://webreview.com/pub/98/09/11/feature/sidebar2.html > |
| [5] | ISO/IEC DIS 16262, ECMAScript:A general purpose, cross platform programming language, 1. ed, 98s, 1998 |
| [6] | JavaScript World, Tutorials->ECMAScript, [viitattu 3.11.2000]
< http://www.jsworld.com/ecmascript/ > |
| [7] | MARTIN Webb, JavaScript Guinelines and Best Practice, 26.6.1999,
[viitattu 3.11.2000] < http://tech.irt.org/articles/js169/index.htm > |
| [8] | VRML Consortium Incorporated, ISO/IEC 14772-1:1997, The Virtual
Reality Modeling Language, Annex C (normative) ECMAScripting reference,
1997, [viitattu 3.11.2000] < http://tecfa.unige.ch/guides/vrml/vrml97/spec/part1/javascript.html> |