JavaScript设计模式(二)

128 阅读1分钟

二、工厂模式

  • 简单工厂函数:创建一个person对象,调用打印person.name

  • 复杂工厂模式:创建实例,生产person和car实例,使用构造函数

    a. instanceof 会判断后面的构造函数的原型是不是存在在前面这个对象的原型链里

//简单工厂模式
    /*function createPerson(name){
        this.name = name;
        this.getName = function () {
            console.log(this.name);
        }
    }
    let person1 = new createPerson('zhangsan');
    person1.getName();*/
//复杂工厂模式
    function Person(name){
        this.name = name;
    }
    Person.prototype.getName = function(){
        console.log(this.name);
    }

    function Car(module) {
        this.module = module;
    }
    Car.prototype.getModule = function () {
        console.log(this.module)
    };

    function create(type,params) {
        if(this instanceof create){
            return new this[type](params)
        }else{
            return new create(type,params)
        }
    }
    create.prototype = {
        person : Person,
        car: Car
    }
    let person1 = create('person','xiaoming');
    person1.getName();
    let car1 = new create('car','benZ');
    car1.getModule();