Initializers for objects and arrays
Variables may be initialized as objects and arrays using lists inside of "{}" and "[]". By using these initializers, instances of Objects and Arrays may be created without using the new constructor. Objects may be initialized using a syntax similar to the following:
var o = {a:1, b:2, c:3};
This line creates a new object with the properties a, b, and c set to the values shown. The properties may be used with normal object syntax, for example, o.a == 1.
Arrays may initialized using a syntax similar to the following:
var a = [1, 2, 3];
This line creates a new array with three elements set to 1, 2, and 3. The elements may be used with normal array syntax, for example, a[0] == 1.
The distinction between Object and Array initializer might be a bit confusing when using a line with syntax similar to the following:
var a = {1, 2, 3};
This line also creates a new array with three elements set to 1, 2, and 3. The line differs from the first line, Object initializer, in that there are no property identifiers and differs from the second line, Array initializer, in that it uses "{}" instead of "[]". In fact, the second and third lines produce the same results. The elements may be used with normal array syntax, for example, a[0] == 1.
The following code fragment shows the differences.
var o= {a:1, b:2, c:3};
Screen.writeln(typeof o +" | "+ o._class +" | "+ o);
var a = [1, 2, 3];
Screen.writeln(typeof a +" | "+ a._class +" | "+ a);
var a= {1, 2, 3};
Screen.writeln(typeof a +" | "+ a._class +" | "+ a);
The display from this code is:
object | Object | [object Object]
object | Array | 1,2,3
object | Array | 1,2,3
As shown in the first display line, the variable o is created and initialized as an Object. The second and third lines both initialize the variable a as an Array. Notice that in all cases the typeof the variable is object, but the class, which corresponds to the particular object and which is reflected in the _class property, shows which specific object is created and initialized.
Methods - assigning functions to objects