Created
January 10, 2020 16:12
-
-
Save r3dm1ke/5bb3b4a396741a7e789be0a5a7ab40d3 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
Line 39 originally
console.log(car.turbocharged);
should be changed toconsole.log(sportsCar.turbocharged);