Variables and Objects |
Active Web |
Script variables are references to script objects. Variables can be created at any time inside a script. If a variable does not exist when it is used then it is automatically created. If a variable has not been assigned any data then its value is null.
Primitives are simple objects that only have a value and do not have any properties. The primitives are null, string, number and boolean. These objects are created with a simple assignment. The null primitive can also be created with just the var operator.
e.g.
var mynull;
var mynull = null;
var mystring = "hello";
var mynumber = 3;
var myboolean = true;
All variables are objects. An object is created either as a primitive (see above) or by using the new operator (see Operators). Primitive objects do not hold properties and do not have any functions, but if a primitive is given a property then it is automatically converted into a full object. This is mostly transparent to you as a script writer but you should be aware that there is a difference between a string primitive and a string object when using the object for condition testing (see Condition Testing).
When an object is given other objects to hold by using the ‘.’ operator they are referred to as its properties. An object can have any number of properties and the properties themselves can have properties allowing complex object models to be built up.
e.g.
var address;
address.street = “Main”;
address.country = “United States”;
address.valid = true;
This example created a primitive null object called ‘address’. It then created a string object called ‘street’ and gave it to the ‘address’ object (this converted the null primitive to a full object with a null value). The example then went on to give the ‘address’ object another string object and a boolean object. Note that the objects ‘street’, ‘country’ and ‘valid’ are only accessible from the ‘address’ object; they cannot be accessed by just using their name on its own. In fact there could be another object using the same variable name either on its own or as a property in another object.
In the example above, the address object was created before the street object was added to it. This is the only way objects can be built up. Attempting to create an object and giving it a property in one statement, e.g. ‘var address.street = "Main" will cause a parse error.
The ‘value’ of an object is a reserved word and should not be used as a variable name. The value is the content of the object. In the example above the ‘value’ of address.street is ‘Main’ and can be referenced either as address.street or as address.street.value.
Topic ID: 150114