prototype examples

by Anchit Gupta

HTML

<div class="heading">
Prototype examples
</div>

CSS

body{
  background: #fff;
}
.heading{
  font-size: 25px;
  text-align: center;
}

JavaScript

//Vehicle constructor
function Vehicle(vehicleType){
	this.vehicleType = vehicleType;
}

Vehicle.prototype.blowHorn = function(){
	console.log("blow horn!!");
}

//Bus constructor
function Bus(make){
	Vehicle.call(this, "Bus");
	this.make = make;
}

// Bus constructor inherit properties from Vehicle Prototype Object
//Object.create(Vehicle.prototype) will create an empty object whose prototype is Vehicle.prototype which We set this object as a prototype of Bus
Bus.prototype = Object.create(Vehicle.prototype);

Bus.prototype.numberOfWheels = 6;
Bus.prototype.accelerator = function() {    
	console.log('Accelerating Bus'); //Bus accelerator
}
Bus.prototype.brake = function() {    
	console.log('Braking Bus'); // Bus brake
}

function Car(make) {  
	Vehicle.call(this, "Car");  
  this.make = make;
}

Car.prototype = Object.create(Vehicle.prototype);

Car.prototype.noOfWheels = 4;
Car.prototype.accelerator = function() {    
	console.log('Accelerating Car');
}
Car.prototype.brake = function() {    
	console.log('Braking Car');
}

function MotorBike(make) {  
	Vehicle.call(this, "MotorBike");  
  this.make = make;
}

MotorBike.prototype = Object.create(Vehicle.prototype);

MotorBike.prototype.noOfWheels = 2;
MotorBike.prototype.accelerator = function() {    
	console.log('Accelerating MotorBike');
}
MotorBike.prototype.brake = function() {    
	console.log('Braking MotorBike');
}

var myBus = new Bus('Mercedes');
var myCar = new Car('BMW');
var myMotorBike = new MotorBike('Honda');

console.log(myBus instanceof Bus); //true
console.log(myBus instanceof Vehicle); //true

Object.getPrototypeOf(myBus) == Bus.prototype // true