Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Bug in Factory Pattern #203

Open
samjross opened this issue Oct 2, 2016 · 0 comments
Open

Bug in Factory Pattern #203

samjross opened this issue Oct 2, 2016 · 0 comments

Comments

@samjross
Copy link

samjross commented Oct 2, 2016

Reading this right here, the Factory Pattern section.

    // Our default vehicleClass is Car
    VehicleFactory.prototype.vehicleClass = Car;

    // Our Factory method for creating new Vehicle instances
    VehicleFactory.prototype.createVehicle = function ( options ) {

      switch(options.vehicleType){
        case "car":
          this.vehicleClass = Car;
          break;
        case "truck":
          this.vehicleClass = Truck;
          break;
        //defaults to VehicleFactory.prototype.vehicleClass (Car)
      }

      return new this.vehicleClass( options );

    };

You say that this.vehicleClass defaults to Car, but in practice, the first time you do it it default to car but every other time it defaults to whatever class you instantiated last. Try making a truck and then a car:

  // Create an instance of our factory that makes cars
  var carFactory = new VehicleFactory();

  var truck = carFactory.createVehicle( {
      vehicleType: "truck",
      color: "yellow",
      doors: 6 } );

  var car = carFactory.createVehicle( {
      color: "yellow",
      doors: 6 } );

  // Test to confirm our car was created using the vehicleClass/prototype Car

  // Outputs: false
  console.log( car instanceof Car );

  console.log( car );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants