Last active
July 10, 2023 04:51
-
-
Save Samjin/356ab36787ee66971cf6a351b25e5365 to your computer and use it in GitHub Desktop.
Constructor and prototypeFactory
This file contains hidden or 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 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