我有一个我正在玩的小工厂模式示例,它工作正常,并为我提供了一种使用通用接口创建相关对象的方法:
$(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);
});
来自 C#,这看起来很熟悉,我很容易理解。然而,我也倾向于尝试站在巨人的肩膀上,Doug Crockford 对新事物说不。
我怎么能重构这个代码来使用Object.create
而不是新的。对普通人来说真的很重要,还是仅仅因为上层说重要才重要?