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();
TypeScript
 class Car{
    speed: String;
    setSpeed(speed: string) {
        this.speed = speed;
        alert("Car speed changed");
    }
 }

class Ferrari extends Car{
    speed: String;
    setSpeed(speed: string) {
        this.speed = speed;
        alert("Farrari speed changed");
    }
}

var car = new Ferrari();
car.setSpeed('');

results matching ""

    No results matching ""