构造器模式

基于面向对象的类和实例来实现的,每个实例都是一个单独的空间,其中有自己私有的属性方法,互不影响。也可以调用公共的属性方法

  1. // AModule类
  2. class AModule {
  3. constructor (){
  4. // 实例的私有属性,this是指类的实例
  5. this.arr = []
  6. }
  7. // 原型上的公共方法
  8. change (val) {
  9. this.arr.push(val)
  10. }
  11. }
  12. let module1 = new AModule
  13. let module2 = new AModule

工厂模式

根据不同条件实现不同的处理逻辑
简单的工厂模式

  1. function factory(options){
  2. const { type } = options
  3. switch (type){
  4. case 'arrya':
  5. // ...
  6. break
  7. case 'object':
  8. // ...
  9. break
  10. }
  11. }
  12. factory({type: 'array'})
  13. factory({type: 'object'})

jquery中的工厂模式

  1. (function () {
  2. var jQuery = function (selector, context) {
  3. // 创建init类的实例
  4. return new jQuery.fn.init(selector, context);
  5. };
  6. jQuery.fn = jQuery.prototype = {
  7. // ...
  8. };
  9. // 需要工厂的转换
  10. var init = jQuery.fn.init = function (selector, context, root) {};
  11. init.prototype = jQuery.fn;
  12. window.$ = jQuery;
  13. })();
  14. $('xxx'); //-> jQuery('xxx') 创建JQ类的实例,调取jQuery.fn原型上的方法