-
-
Save namviet3210/4e73dbc57d1f98931740d9a747086422 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(sportsCar.turbocharged); // true <= This part is to test sportsCar, so change the object from car to sportsCar |
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);