I've got a little factory pattern example I'm playing with that works fine and gives me a way to create related objects with a generic interface:
$(document).ready(function () {
function Car(options) {
this.color = options.color || 'unknown',
this.name = options.carName || 'unknown',
this.doors = options.doors || 4;
}
function Truck(options) {
this.color = options.color || 'unknown',
this.name = options.name || 'unknow',
this.doors = options.doors || 2;
}
function VehicleFactory() { };
VehicleFactory.prototype.createVehicle = function (options) {
if (options.vehicleType === 'car') {
return new Car(options);
}
else {
return new Truck(options);
}
}
var factory = new VehicleFactory();
var car = factory.createVehicle({
vehicleType: 'car',
name: 'bill',
doors: 2
});
console.log(car instanceof Car);//true
var truck = factory.createVehicle({
vehicleType: 'truck',
doors: 3
});
//checks to make sure that objects are of the right type
console.log('truck is an instance of Car: ' + (truck instanceof Car)); //false
console.log('truck is an instace of Truck: ' + (truck instanceof Truck)); //true
console.log(truck);
});
Coming from C# this looks familiar enough and it easy for me to grok. However, I also tend to try to stand on the shoulders of giants and Doug Crockford said no to new.
How could I refactor this code to use Object.create
instead of new. Does it REALLY matter to the average person, or does it only matter because the upper echelon says it does?