Skip to content

Instantly share code, notes, and snippets.

@r3dm1ke
Created January 10, 2020 16:12
Show Gist options
  • Save r3dm1ke/5bb3b4a396741a7e789be0a5a7ab40d3 to your computer and use it in GitHub Desktop.
Save r3dm1ke/5bb3b4a396741a7e789be0a5a7ab40d3 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
@namviet3210
Copy link

Line 39 originally console.log(car.turbocharged); should be changed to console.log(sportsCar.turbocharged);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment