Skip to content

Instantly share code, notes, and snippets.

@allanphilipbarku
Forked from r3dm1ke/Car.js
Created January 16, 2020 09:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save allanphilipbarku/dd87ab988e3bf8f13b6a38957158dcce to your computer and use it in GitHub Desktop.
Save allanphilipbarku/dd87ab988e3bf8f13b6a38957158dcce to your computer and use it in GitHub Desktop.
Car class in ES5
// "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