工厂函数能够创建对象,并且函数是()执行不是new执行。
简单工厂模式
function createStudents(name,age,sex) {
return {
name : name,
age : age,
sex : sex,
study : function () {
console.log("语数英理化生")
}
}
}
var xiaoming = createStudents("小明",20,"男")
console.log(xiaoming)
简单工厂模式不能 使用instanceof,因为不是new执行的
一般工厂模式
function Car(color,doors) {
this.color = color;
this.doors = doors;
console.log("这是一辆"+this.color+"色的卡车,它有"+this.doors+"扇门");
}
function createFactory(color,doors) {
return new Car(color,doors);
}
var car1 = new createFactory("白",4);
var car2 = new createFactory("黑",2);
console.log(car1 instanceof Car);//true
这里感觉是多此一举,但是工厂模式是面向接口编程。
简单工厂模式
function Car(color,doors) {
this.color = color;
this.doors = doors;
console.log("这是一辆"+this.color+"色的卡车,它有"+this.doors+"扇门");
//这里需要retur自己出去,因为工厂函里是 Car 圆括号直接执行,不是new 执行 不会自动return
return this;
}
function Suv(seat) {
this.seat = seat;
console.log("这是一辆"+this.seat+"座的SUV")
return this;
}
function Bus(position,fullLoad) {
this.position = position;
this.fullLoad=fullLoad;
console.log("这是一辆"+this.position+"的公交车,满座人数是"+this.fullLoad+"人");
return this;
}
function createFactory(type) {
//通过type判断,如果是Car则创建 car 如果是Suv 则创建SUV............
if(type == "Car"){
//apply 指定执行上下文
return Car.apply(new Car(),[].slice.call(arguments,1));
}
if(type == "Suv"){
return Suv.apply(new Suv(),[].slice.call(arguments,1))
}if(type == "Bus"){
return Bus.apply(new Bus(), [].slice.call(arguments,1))
}
}
var car = new createFactory("Car","白",4);
var suv = new createFactory("Suv",7);
var suv = new createFactory("Bus","北京",55);
console.log(car instanceof Car);//true
console.log(car instanceof createFactory);//false