Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- function Car(options) {
- this.doors = options.doors || 4;
- this.color = options.color || "white";
- this.state = options.state || "brand new";
- }
- function Truck(options) {
- this.wheelSize = options.wheelSize || 4;
- this.color = options.color || "black";
- this.state = options.state || "used";
- }
- function VehicleFactory() { };
- // default vahicle class
- VehicleFactory.prototype.vehicleClass = Car;
- VehicleFactory.prototype.createVehicle = function (options) {
- if (options.vehicleType === "car") {
- this.vehicleClass = Car;
- } else {
- this.vehicleClass = Truck;
- }
- return new this.vehicleClass(options);
- };
- var carFactory = new VehicleFactory();
- var car = carFactory.createVehicle({
- vehicleType: "car",
- doors: 5,
- color: "red"
- });
- console.log(car instanceof Car);
- console.log(car);
- //modify
- var movingTruck = carFactory.createVehicle({
- vehicleType: "truck",
- wheelSize: 8,
- color: "blue"
- });
- console.log( movingTruck instanceof Truck );
- console.log(movingTruck);
- // new factory for trucks
- function TruckFactory () {}
- TruckFactory.prototype = new VehicleFactory();
- TruckFactory.prototype.vehicleClass = Truck;
- var truckFactory = new TruckFactory();
- var myBigTruck = truckFactory.createVehicle( {
- state: "bad",
- color: "pink",
- wheelSize: "big" } );
- console.log( myBigTruck instanceof Truck );
- console.log( myBigTruck );
Advertisement
Add Comment
Please, Sign In to add comment