-
-
Save allanphilipbarku/dd87ab988e3bf8f13b6a38957158dcce to your computer and use it in GitHub Desktop.
Car class in ES5
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// "class" declaration | |
function Car(make, model) { | |
this.make = make; | |
this.model = model; | |
} | |
// the start method | |
Car.prototype.start = function() { | |
console.log('vroom'); | |
} | |
// overriding the toString method | |
Car.prototype.toString = function() { | |
console.log('Car - ' + this.make + ' - ' + this.model); | |
} | |
// inheritance example | |
function SportsCar(make, model, turbocharged) { | |
Car.call(this, make, model); | |
this.turbocharged = turbocharged; | |
} | |
// actual inheritance logic | |
SportsCar.prototype = Object.create(Car.prototype); | |
SportsCar.prototype.constructor = SportsCar; | |
// overriding the start method | |
SportsCar.prototype.start = function() { | |
console.log('VROOOOM'); | |
} | |
// Now testing the classes | |
var car = new Car('Nissan', 'Sunny'); | |
car.start(); // vroom | |
console.log(car.make); // Nissan | |
var sportsCar = new SportsCar('Subaru', 'BRZ', true); | |
sportsCar.start(); // VROOOOM | |
console.log(car.turbocharged); // true |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment