HTML and CSS Reference
In-Depth Information
Figure 8.12 The book object's properties.
8.5 Extending Objects with Prototypes
In object-oriented languages, like Java and C++, the object, along with its properties
(state) and methods (behavior), is bundled up into a container called a class. These pro-
gramming languages all allow classes to reuse and extend an existing class; that is,
inherit commonly used state and behaviors from other classes. A new class, called a sub-
class, can be derived from an existing class. For example, if you have a Pet class, let's say
all pets have an owner, a gender, and some methods for setting and getting the proper-
ties. We could create subclasses of the Pet, such as a Dog and Cat, because both the Dog
and Cat share the same properties as a Pet. The code for the Pet can be extended to the
Dog and the Cat by using inheritance. Then each subclass can be refined further by add-
ing its own specific features.
Let's look at an example of how JavaScript might use inheritance. A constructor func-
tion called divStyle() has been defined. It will be used to create div containers to style a
Web page. The constructor defines the properties for a div , for example, the borders, pad-
ding, background color, and so on, and has a divGet() method to display the div in the
document. Later we want to make divStyle objects but change or add properties; perhaps
change the width of the border or set a border color. We can reuse or extend the divStyle
code by using inheritance.
Section 8.2 explained that unlike Java and C++, JavaScript doesn't have a class mech-
anism per se, but inheritance involves reusing or extending a class. With JavaScript we
can simulate a class with a constructor function and the new keyword. And to imple-
ment inheritance JavaScript extends a the class with a prototype . (For those of you who
are Java or C++ programmers, JavaScript does not use keywords like extended , protected ,
private, public , etc.). How does prototype inheritance work?
JavaScript functions are automatically given an empty prototype object. If the function
acts as a constructor function for a class of objects, the prototype object can be used to
extend the class. Each object created for the class is also given two properties, a constructor
property and a prototype property. The constructor property is a reference to the function that
created this object, and the prototype property a reference to its prototype object. This prop-
erty allows the object to share properties and methods.
Search WWH ::

Custom Search