Generally objects may be created using the following syntax:
name = new Object()
For instance Array, Date, Number, Boolean, and String objects can be created this way as in the example below. Most objects may be created this way except for the Math object which cannot be instantiated (an instance of it may not be created).
ratings = new Array(6,9,8,4,5,7,8,10)
var home = new String("Residence")
var futdate = new Date()
var num1 = new Number()
String objects may also be created as follows:
var string = "This is a test."
Objects are created using templates. Templates to objects are like cookie cutters to cookies. Cookie cutters are used to create instances of cookies and object templates are used to create instances of objects. For now, the template is shown.
The following creates an object, olist.
this.elements = elements
this.listitems = new Array(elements)
this.getItem = list_getItem
this.setItem = list_setItem
The methods list_setItem and list_getItem are written as follows:
function list_setItem(element, stringval)
this.listitems(element) - stringval
Creating the Object
var list1 = new olist(10)
Changing the Object
list1.setItem(0,"This is the first item in the list")
list1.setItem(1,"This is the second item in the list")
list1.setItem(2,"This is the third item in the list")
The Prototype property
The prototype property can be used to create new properties of created objects (whether they are user defined or system defined) as follows:
list1.prototype.type = "1"
The Function Constructor
minus2 = new Function("x","return x-2")
y = minus2(10)
The value of y is now 8.
alert("An error occurred!")
window.alert("An error occurred!")
The following code using the "this" object declaration will perform the same:
this.alert("An error occurred!")
Object and Property Reference
Objects and their properties are normally referenced using a dot between each object or its property or method. as follows:
document.write("This is a test.")
However, a method called array notation, may be used. Array notation is required when the first character of a property name is a digit since the dot method may not be used in this case. The above example in array notation is:
document ["write"] ("This is a test.")
Levels of Objects
- Top level objects
- Objects that are properties of other objects
- Objects that are not properties of other objects