JavaScript - Custom Objects
In a Nutshell - CIW Course Section 2, Part A2, Chapter 6
Custom Objects
I think that the course over-complicates custom objects with the use of terminology like: constructors and instantiating, A custom object, in it's simplest terms, is just a collection of related functions.
"this" keyword
The "this" keyword is central to creating a custom object, and it's use is what differentiates a simple function from a constructor, or object creation function. Consider the following code:
| function widgetObject(code, colour, size) { this.code = code; this.colour = colour; this.size = size; } |
This routine is referred to as a constructor because it will allow the creation of a new object. The presence of the function does not create the object, it must be called and assigned to a new object. The "this" keyword has allowed the defining of properties for the object.
| redWidget = new widgetObject(21, "Red", 4); |
The line of code above has now created a new object called redWidget, which is an object of type widgetObject. And redWidget has three properties: code, colour and size.
Custom Methods
During the object creation we have assigned properties to the object, In a similar manner we can assign a method:
| function widgetObject(code, colour, size) { this.code = code; this.colour = colour; this.size = size; this.showMe = showMe; } |
this is the same constructor as before, but we have added a line. showMe will become a method, provided we have a function named showMe within the context.
| function showMe() { var dStr = ""; dStr = "Code: " + this.code + "\n"; dStr += "Colour: " + this.colour + "\n"; dStr += "Size: " + this.size; alert(dStr); return false; } |
Note the use of the "this" keyword in the method function. While this is not essential for an object method, it does allow the use of the object properties in the method.
| onClick="return redWidget.showMe();" |
The above line of code is an example of how the widget method may be invoked. The buttons below use this coding to test the method for each of our custom objects.
Complex Objects
A complex custom object differs from a simple custom object in that a simple object has only one level of properties, a complex object may have many. A complex object will have properties which are, themselves, custom objects.

