JSFiddle - React, Tailwind, and code Playground

by deepak sisodiya

JavaScript

// prototypal inheritance in javascript....sahi wala

//Vehicle Class
function Vehicle(hasEngine, hasWheels) {
    this.hasEngine = hasEngine || false; 
    this.hasWheels = hasWheels || false;
}

//Vehicle Class Methods
Vehicle.prototype = {
    start: function(){
        if(this.hasEngine === true && this.hasWheels === true){
            alert("Gur Gur Gur, I am running")
        }else{
            if(this.hasEngine === false){
                alert("I cannot Start, I do not have Engine");
            }
            if(this.hasWheels === false){
                alert("I cannot Start, I do not have Wheels");
            }
        }
    }
}

//Car Class
function Car (make, model, hp, hasEngine, hasWheels) { 
    ////You Forget to call Base Class constructor 
    //Step 1  (calling Base call constructor with proper param)==>
    Vehicle.call(this, hasEngine, hasWheels);
    //Step 1  <==
    
    this.hp = hp;
    this.make = make;
    this.model = model;
}
/////Car.prototype = new Vehicle is Wrong ,

//Step 2  (Extending ChildClass Prototype from BaseClass prototype) ==>

Car.prototype = Object.create(Vehicle.prototype);
//Step 2  <==

//Car Class Methods
Car.prototype.displaySpecs = function () { 
    alert(this.make + ", " + this.model + ", " + this.hp + ", " 
    + this.hasEngine + ", " + this.hasWheels);
}
//Step 3  ==>
Car.prototype.constructor = Car;
//Step 3  <==

//====================Now we can use Car Class =================

var myAudi = new Car ("Audi", "A4", 150, true, true);
myAudi.displaySpecs();
//Now I am calling a Parent Class method on Child class object
myAudi.start();


var myKhtara = new Car ("Khatara", "1990", 50, false, false);
myKhtara.displaySpecs();
//Now I am calling a Parent Class method on Child class object
myKhtara.start();