Inheritance in JavaScript
JavaScript supports single class inheritance. To create a child class that inherit parent class, we create a Parent class object and assign it to the Child class. In following example we created a child class Ferrari from parent class Car.
JavaScript
//Define the Car class
function Car() { }
Car.prototype.speed= 'Car Speed';
Car.prototype.setSpeed = function(speed) {
this.speed = speed;
alert("Car speed changed");
}
//Define the Ferrari class
function Ferrari() { }
Ferrari.prototype = new Car();
// correct the constructor pointer because it points to Car
Ferrari.prototype.constructor = Ferrari;
// replace the setSpeed method
Ferrari.prototype.setSpeed = function(speed) {
this.speed = speed;
alert("Ferrari speed changed");
}
var car = new Ferrari();
car.setSpeed();