Skip to content

Instantly share code, notes, and snippets.

@Samjin
Last active July 10, 2023 04:51
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 Samjin/356ab36787ee66971cf6a351b25e5365 to your computer and use it in GitHub Desktop.
Save Samjin/356ab36787ee66971cf6a351b25e5365 to your computer and use it in GitHub Desktop.
Constructor and prototypeFactory
class Car {
constructor(options) {
this.doors = options.doors || 4;
this.state = options.state || "brand new";
this.color = options.color || "silver";
}
}
class Truck {
constructor(options) {
this.state = options.state || "used";
this.wheelSize = options.wheelSize || "large";
this.color = options.color || "blue";
}
}
class VehicleFactory {
constructor() {
this.vehicleClass = Car;
}
createVehicle(options) {
if (options.vehicleType === "car") {
this.vehicleClass = Car;
} else {
this.vehicleClass = Truck;
}
return new this.vehicleClass(options);
}
}
const carFactory = new VehicleFactory();
const car = carFactory.createVehicle({ vehicleType: "car", color: "yellow", doors: 6 });
console.log(car instanceof Car); // Outputs: true
console.log(car); // Outputs: Car object of color "yellow", doors: 6 in a "brand new" state
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment