HTML and CSS Reference
In-Depth Information
EXPLANATION ( CONTINUED )
3
The setOwner and getOwner methods are defined for the Pet. All Pet objects will
have access to these methods.
4
The setGender and getGender methods are defined for the Pet .
5
An empty function called Cat is declared. It will be used as the constructor func-
tion for a Cat class.
6
By creating a new Pet object and assigning it to the Cat's prototype , all properties
and methods of the Pet will now be available to the Cat. This is how JavaScript
implements inheritance.
7
The constructor property returns a reference to the function that initialized the ob-
ject; in this case, the Pet. (The value of this property is a reference to the function
itself, not a string containing the function's name). By updating the constructor
property, it will contain a reference to the new Cat class constructor, not its parent,
the Pet. Now the Cat constructor is the constructor for all Cat objects.
8
We are creating a new method for the Cat , called speak . It will be a property of the
Cat's prototype. All cat objects will have access to this method and all cats will
speak “Meow”.
9
An empty function, called Dog , is created.
10
By creating a new Pet object and assigning it to the Dog's prototype , all properties
and methods of the Pet will now be available to the Dog . The Dog inherits from
the Pet . The constructor property is also updated so that it will reference the Dog
class. The Dog will also have a speak() method. How does JavaScript know which
speak() method to call? The object that calls this speak method has its own copy
of it.
11
A new object called cat is instantiated. And in the next line, a dog object is instan-
tiated. They both inherit from the Pet class.
12
The cat object calls the setOwner() method with a new value. It inherited this
method from the Pet .
13
The dog calls the setGender() method, inherited from the Pet .
14
Using the getOwner() and getGender() and speak() methods, we display the prop-
erties of the cat object and the dog object. The output is shown in Figure 8.20.
Figure 8.20 Subclasses and their properties.
 
Search WWH ::




Custom Search