|
JavaScript 2.0
Core Language
Variables
|
Wednesday, February 16, 2000
A variable defined with var can be modified, while one defined with const
is read-only. 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 AssignmentExpression
is not provided in a var definition, then undefined is assumed; if undefined
cannot be coerced to type t then any attempt to read the variable
prior to writing a valid value into it will result in an error. 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 NaN var e:Type=Boolean; var f:Number=undefined; // coerced to NaN var g:Boolean=undefined; // coerced to false var h:int=undefined; // coerced to int(0)
const means that Identifier
cannot be written after its value is set. Its value can be set by an AssignmentExpression
if one is provided. If one is not provided then the constant can be written exactly once using a regular assignment statement;
any attempt to read the constant prior to writing its value will result in an error. For example:
const c:Integer;
function f(x) {return x+c}
f(3); // error: c's value is not defined
c = 5;
f(3); // returns 8
c = 5; // error: redefining c
Just like any other definition, a constant may be rebound after leaving its scope. For example, the following is legal;
j is local to the block, so 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 Wednesday, February 16, 2000 |