Skip to content

Instantly share code, notes, and snippets.

@jf990
Created April 7, 2020 17:19
Show Gist options
  • Save jf990/c548f47bc7e34a0180b0c8ea0b6d0279 to your computer and use it in GitHub Desktop.
Save jf990/c548f47bc7e34a0180b0c8ea0b6d0279 to your computer and use it in GitHub Desktop.
JavaScript class pattern
/**
* Example JavaScript code to demonstrate how to compose classes.
* This requires ES6 syntax.
*
* `Transportation` is a base class that is intended to have classes derived from it.
* Derived classes are expected to manage the base class properties and add their own.
* In each constructor, `super` is called first to allow the base class to perform its state
* initialization before the derived class do its, allowing the derived class to override
* anything done in the base class constructor.
*/
class Transportation {
type = "vehicle";
id = "1";
constructor(attributes) {
this.model = attributes.model || "unknown";
this.make = attributes.make || "unknown";
this.year = attributes.year || new Date().getFullYear();
this.passengerCount = attributes.passengerCount || 0;
}
getType() {
return this.type;
}
getPassengerCount() {
return this.passengerCount;
}
}
class Boat extends Transportation {
constructor(attributes) {
super(attributes);
this.weight = attributes.weight || 0;
this.type = "Boat";
}
}
class Automobile extends Transportation {
constructor(attributes) {
super(attributes);
this.fuelType = attributes.FuelType;
this.type = "Automobile";
}
}
class Bus extends Transportation {
constructor(attributes) {
super(attributes);
this.type = "Bus";
}
}
class Airplane extends Transportation {
constructor(attributes) {
super(attributes);
this.type = "Airplane";
}
}
let yacht = new Boat({
year: 1922,
make: "Chriscraft",
model: "DreamLiner",
passengerCount: 12
});
let bus = new Bus({
year: 1963,
make: "Novel",
model: "BigBus",
passengerCount: 54
});
let jet = new Airplane({
year: 1999,
make: "Boeing",
model: "737 MAX",
passengerCount: 187
});
let unknown = new Transportation({});
// let results = document.getElementById("results");
// results.innerHTML = `<h3>${yacht.getType()}</h3><p>${yacht.year} ${yacht.make} Passengers: ${yacht.getPassengerCount()}</p><h3>${bus.getType()}</h3><p>${bus.make} Passengers: ${bus.getPassengerCount()}</p><h3>${jet.getType()}</h3><p>${jet.make} Passengers: ${jet.getPassengerCount()}</p><p>Unknown transportation: ${JSON.stringify(unknown)}</p>`;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment