Book Image

Learning Object-Oriented Programming

By : Gaston C. Hillar
Book Image

Learning Object-Oriented Programming

By: Gaston C. Hillar

Overview of this book

Table of Contents (16 chapters)
Learning Object-Oriented Programming
About the Author
About the Reviewers

Working with the prototype-based inheritance in JavaScript

First, we will create a constructor function in JavaScript and define properties and methods in its prototype. Then, we will take advantage of prototype-based inheritance in order to create objects that specialize the behavior defined in the baseline prototype. We will override methods and properties.

Creating objects that specialize behavior in JavaScript

Now it is time to code objects in JavaScript. The following code defines the Animal empty constructor function in JavaScript, followed by the declaration of properties and functions for the Animal prototype:

function Animal() {}

Animal.prototype.numberOfLegs = 0;
Animal.prototype.pairsOfEyes = 0;
Animal.prototype.age = 0;

Animal.prototype.printLegsAndEyes = function() {
  console.log("I have " + this.numberOfLegs + " legs and " + this.pairsOfEyes * 2 + " eyes.");

Animal.prototype.printAge = function() {
  console.log("I am " + this.age + " years old.");

In this case, we will...