|
JavaScript 2.0
Core Language
Variables
|
Thursday, November 11, 1999
The general syntax for defining variables is:
var Identifier [: TypeExpression] [= AssignmentExpression] , ... , Identifier [: TypeExpression] [= AssignmentExpression] ;const Identifier [: TypeExpression] = AssignmentExpression , ... , Identifier [: TypeExpression] = AssignmentExpression ;A variable defined with var can be modified, while one defined with const
cannot. Identifier is the name of the variable and TypeExpression
is its type. Identifier can be any non-reserved identifier. TypeExpression
is evaluated at the time the variable definition is evaluated and should evaluate to a type t.
If provided, AssignmentExpression gives the variable's initial value v. If not,
undefined is assumed; an error occurs if undefined cannot be coerced
to type t. AssignmentExpression is evaluated just after the TypeExpression
is evaluated. The value v is then coerced to the variable's type t and stored in the variable. If the
variable is defined using var, any values subsequently assigned to the variable are
also coerced to type t at the time of each such assignment.
Multiple variables separated by commas can be defined in the same VariableDefinition. The values of earlier variables are available in the TypeExpressions and AssignmentExpressions of later variables.
If omitted, TypeExpression defaults to type any. Thus, the definition
var a, b=3, c:integer=7, d, e:type=boolean, f:number, g:e, h:int;
is equivalent to:
var a:Any=undefined; var b:Any=3; var c:integer=7; var d:integer=undefined; // coerced to +0 var e:type=boolean; var f:number=undefined; // coerced to +0 var g:boolean=undefined; // coerced to false var h:int=undefined; // coerced to int(0)
const Definitionsconst means that Identifier cannot be written after
it is defined. It does not mean that Identifier will have the same value the next time it is
bound. For example, the following is legal; a new j binding is created each time through the loop:
var k = 0;
for (var i = 0; i < 10; i++) {
local const j = i;
k += j;
}
|
Waldemar Horwat Last modified Thursday, November 11, 1999 |