工厂模式

  • 注重创建对象的整体思路,不关心你想创建的对象是什么样的,因为想创建的模板是已经做好的了。
  • 只要我们将想要从工厂模式中去创建哪种模板,通过参数传递给工厂函数,那么工厂函数就可以生成出对应的对象 ```javascript function Person(name) { this.name = name; } Person.prototype.getName = function(){ console.log(this.name); }

function Car(model){ this.model = model; } Car.prototype.getModel = function(){ console.log(this.model); }

function create(type, param){ if(this instanceof create) { // instanceof 会判断后面的构造函数的原型,是不是在前面的对象的原型链里 //用new create创建的对象 return new thistype; }else { //用create直接创建对象 return new create(type, param); }

} create.prototype = { person: Person, car: Car }

var person1 = new create(‘person’,’张三’);

console.log(person1); person1.getName();

/* new create(‘person’, ‘张三’) ->{ proto: create.prototype }

  1. // 然后执行 new this[type](param)
  2. new this[type](param) === new Person('张三') -> {
  3. __proto__: Person.prototype,
  4. this.name = '张三'
  5. }

*/

var car1 = create(‘car’, ‘Benchi’); console.log(car1); ```