Object Inheritance
In this lesson, we learn how object inheritance works in JavaScript. Let's begin! :)
We'll cover the following...
Object-oriented programming is unimaginable without inheritance. While most languages support several types of inheritance like implementing interfaces, deriving new types from existing ones, overriding methods, etc., JavaScript supports only implementation inheritance, where actual methods are inherited.
Due to the flexibility and dynamism of JavaScript, there are a number of ways you can implement inheritance. In this section, you’ll learn about the two most commonly used patterns, prototype chaining and pseudo-classical inheritance.
Prototype chaining uses a simple trick: you can change the default prototype of a function to an object of your own.
The Listing below demonstrates this technique. It defines three object types (via three constructor functions), Vehicle
, as the base type, and Car
and Boat
as derived types. Observe that derived types set their prototypes to an instance of Vehicle
.
Listing: Prototype chaining
<!DOCTYPE html> <html> <head> <title>Prototype chaining</title> <script> // --- Base type var Vehicle = function () { this.vendor = "Toyota"; }; // --- Base type behavior Vehicle.prototype.getVendor = function() { return this.vendor; }; Vehicle.prototype.getType = function() { return "vehicle"; }; // --- Derived type var Car = function() { this.wheel = 4; }; // --- Chain to base type Car.prototype = new Vehicle(); // --- Override behavior Car.prototype.getType = function() { return "car"; }; // --- Derived type var Boat = function() { this.propeller = 1; }; // --- Chain to base type Boat.prototype = new Vehicle(); // --- Override behavior Boat.prototype.getType = function() { return "boat"; }; // --- Test var car = new Car(); var boat = new Boat(); console.log("It's a " + car.getType()); console.log(car.getVendor()); console.log("wheels: " + car.wheel); console.log("It's a " + boat.getType()); console.log(boat.getVendor()); console.log("props: " + boat.propeller); </script> </head> <body> Listing 8-19: View the console output </body> </html>
When you run this code, ...