// 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();
Please Whitelist JSFiddle in your content blocker.
Help keep JSFiddle free for always by one of two ways:
Whitelist JSFiddle in your content blocker (two clicks)
Go PRO and get access to additional PRO features →
Join the 4+ million users, and keep the JSFiddle dream alive.
Ad-free
All ads in the editor and listing pages are turned completely off.
Use pre-released features
You get to try and use features (like the Palette Color Generator) months before everyone else.
Fiddle collections
Sort and categorize your Fiddles into multiple collections.
Private collections and fiddles
You can make as many Private Fiddles, and Private Collections as you wish!
Console
Debug your Fiddle with a minimal built-in JavaScript console.