HTML and CSS Reference
In-Depth Information
You cannot simply add these new properties to objects that have been created from the Ve-
hicle class; you must first create a new class (called Truck), and extend the Vehicle class.
Only when the class structure is in place can you begin creating instances of Trucks.
A further feature of classes is that they must be defined when the application is compiled;
they cannot be defined on the fly at run-time. It is not possible to decide midway through
program execution that you would like to start capturing an additional property on some
objects.
JavaScript has a far more flexible attitude to classes and objects, in fact classes are not es-
sential to JavaScript programming at all.
The simplest way you can create a new object in JavaScript is as follows:
> obj = {}
The typeof operator confirms that the obj variable is indeed an object:
> typeof obj
"object"
If you are familiar with classical object orientated languages you may wonder what type
obj is? This object is not of any type; it is just an object.
It may sound difficult to write code without knowing the type. For instance, if a function is
passed an object without knowing its type, how does it know what to do with it?
JavaScript uses an approach colloquially known as “duck typing”. There is an old saying,
“if it walks like a duck, and swims like a duck, and quacks like a duck, it probably is a
duck”. Likewise, in JavaScript we might say “If it has a registration number property, and
has a year of registration property, it probably is a vehicle”.
An empty object with no properties or methods is not very useful. With JavaScript
however, it is possible to dynamically add properties and methods:
> obj.firstName = 'John';
> obj.lastName = 'Smith';
> obj.age = 32;
Search WWH ::




Custom Search