<!DOCTYPE html> <html lang= "en" > <head> <meta charset= "UTF-8" > <title>Document</title> </head> <body> <script> //先定义几种车 构造函数 工厂方法 function Car(options) { this .doors = options.doors || 4 ; this .state = options.state || "brand" ; this .color = options.color || "silver" ; } function Truck(options) { this .state = options.state || "used" ; this .wheelSize = options.wheelSize || "large" ; this .color = options.color || "blue" ; } //再定义生产车辆的工厂 function VehicleFactory() {} //定义该工厂生产的默认汽车类型 VehicleFactory.prototype.vehicleClass = Car; //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" , color: "yellow" , doors: 6 }); //验证车是否是这个Car类型的车 console.log(car instanceof Car); //验验车,看看货 console.log(car); //再生产另一部车 var movingTruck = carFactory.createVehicle({ vehicleType: "truck" , state: "like new" , color: "red" , wheelSize: "small" }); //验证车是否是Track类型的车 console.log(movingTruck instanceof Truck); //验验车,看看货 console.log(movingTruck); //----------------------------------------------- //定义第二个工厂 是上面那个工厂的子工厂 function TruckFactory() {} TruckFactory.prototype = new VehicleFactory(); TruckFactory.prototype.vehicleClass = Truck; //创建工厂 var TruckFactory = new TruckFactory(); //生产卡车 var myBigTruck = TruckFactory.createVehicle({ state: "omg..so bad." , color: "pink" , wheelSize: "so big" }); //验验车 console.log(myBigTruck instanceof Truck); //看看货 console.log(myBigTruck); </script> </body> </html> |