addyosmani / addyosmani/essential-js-design-patterns

Bug in Factory Pattern

Aperta
#203 0 commenti 0 reazioni 0 assegnatari Vedi su GitHub
confirmed
Lingua principale
HTML
Stelle
4.9k
Fork
804
Metriche di merge delle PR
Nessuna PR unita negli ultimi 30g

Descrizione

Reading this [right here](https://addyosmani.com/resources/essentialjsdesignpatterns/book/#factorypatternjavascript), the Factory Pattern section.

``` javascript
// 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:

``` javascript
// 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 );
```

Guida per i contributori

Nessuna guida per i contributori indicizzata per questo repository

Valutazione

Questa issue non è ancora stata valutata.

Ricevi le nuove issue nella tua casella

Un breve riepilogo di issue GitHub adatte ai principianti.