听飞狐聊JavaScript设计模式系列14

jopen 8年前

本回内容介绍

上一回,聊了聊状态模式(State),并介绍了一下vue.js;介一回,聊链式编程,模拟一下jQuery,再模拟一下underscore.js,封装一个库。

1. 链式调用

(1) 链式调用是在对象上的方法最后,返回给对象本身,先看一个非链式调用的例子:

var a = alert;  window.onload = function(){      // 定义一个类      function Human(){          // 简单的定义一些方法,吃,撸码...等          this.eat = function(){              a('eat');          };                    this.coding = function(){              a('coding');          };                    this.chase = function(){              a('chase');          }      }      // 定义一个叫大卫的哥们儿      var david = new Human();      // 非链式调用,只能一个一个的调用方法      david.eat();      david.coding()      david.chase();  }

(2) 再把这个例子改成链式调用,当然肯定还是继续玩儿大卫哥咯:

var a = alert;  window.onload = function(){      function Human(){          this.eat = function(){              a('eat');              // 跟上面的例子不同,就是多了这个返回,这里就是链式调用的关键              return this;          };                    this.coding = function(){              a('coding');              return this;          };                    this.chase = function(){              a('chase');              return this;          }      }      var david = new Human();      // 这里就可以实现链式调用了      david.eat().coding().chase();  }

通过这俩例子的对比,很直观的可以看出对象中的方法都返回调用方法实例的引用,简单点说,操作对象,执行方法,更加简洁。看到这里,很多盆友会想到jQuery,没错,下一个例子,简单模拟一下jQuery。

2. 链式调用之模拟jQuery

在系列04的时候,聊过jQuery的extend源码浅析(有兴趣的盆友可以回过头看看系列04),这里我们模拟jQuery的实现,封装一些另外的方法:

<!doctype html>  <html>  <head>      <title>模拟jQuery</title>  </head>  <style>  .middle{      text-align:center;  }  .title{      background-color:black;      color:#f3e14f;      display:inline-block;      font-size:18px;      height:40px;      line-height:40px;      padding:0 50px;  }  </style>  <body>    <div class="middle">      <h5 class="title" id='btn'>登 录</h5>  </div>  <script src='./jQuery.js'></script>  <script>  // 测试部分  $.ready(function(){      var btn= $('btn');      btn.css('background','pink')         .addEvent('click',function(){              btn.css('background','red')         })  })   </script>  </body>  </html>
// 这里是个闭包,防止外部访问  (function(window,undefined){      // 飞狐style,喜欢简写,嘿嘿~      var d = window.document,w = window;      // 私有对象      function _$(arguments){          this.el = [];          // 这里简单的模拟$(id)          for(var i=0,len=arguments.length;i<len;i++){              var el = arguments[i];              if(typeof el === 'string') {                  el = d.getElementById(el);              }              this.el.push(el);          }      }      // 简单的模拟几个方法      _$.prototype = {          constructor:_$,          // 这个写一个简单的遍历,下面的例子聊underscore的时候还会具体聊          each: function(fn) {              for(var i = 0, len = this.el.length; i < len; i++) {                  // call还记得吧,不熟悉的盆友请看系列03之函数                  fn.call(this, this.el[i]);               }              // 这里就是返回到对象,实现链式调用              return this;          },          // 对JS事件基础不熟悉的盆友请看系列08之门面模式          addEvent:function (type,fn){              this.each(function(el) {                  // 这里不考虑兼容低版本的IE                  el.addEventListener(type,fn);              });              return this;          },          // 简单模拟css('','')的写法          css:function (prop,val){              this.each(function(arguments) {                  arguments.style[prop] = val;              });              return this;          }      }            // 初始化准备方法       _$.ready = function (fn){          // 将实例化的_$对象注册到window          w.$ = function(){                return new _$(arguments);            };          // 这里才是开始执行的代码          fn()      }            // 注册全局变量      w.$ = _$;  })(window);    // 将window传入作用域中

这里简单的模拟下jQuery,喜欢jQuery的盆友可以看看源码,网上也有很多哥们儿分享jQuery源码分析的文章。

好像到装逼点儿了,一句话,《芈月传》蒋欣的戏份真特么少:

这一回聊的链式编程,模拟了下jQuery的实现原理,难度较小~下面的内容是我最想分享的,模拟underscore.js,为虾米呢?原因有仨:

1,有可能在项目中根本就不用jQuery,但是你肯定要有一个工具类,类似underscore.js

2,underscore.js有很多方法你根本就用不到,还有就是像系列01里讲的9个方法都是不支持低版本IE的,underscore为了兼容低版本的IE,模拟了这些个方法,如果不考虑兼容低版本IE,就很冗余

3,如上所述,根据项目场景封装一个轻量级的underscore就很有必要了,需要用到underscore的方法时再去源码里找到copy就是了。

3. underscore.js源码分析之实现原理

Underscore是一个非常实用的JavaScript库,提供许多编程时需要的功能的支持,他在不扩展任何JavaScript的原生对象的情况下提供很多实用的功能。

// 跟jQuery一样,闭包实现块级作用域,避免外部访问  (function(){      // 这里的self就是浏览器环境下的window,root就是宿主环境      var root = typeof self == 'object' && self.self === self && self ||              typeof global == 'object' && global.global === global && global ||              this;                    var previousUnderscore = root._;            // 这里是出于安全保护,这个例子代码少,模拟实现,暂时还没用到wrapped,有兴趣的盆友可以看源码      var _ = function(obj) {          if (obj instanceof _) return obj;          if (!(this instanceof _)) return new _(obj);          this._wrapped = obj;      };          // 注册全局变量      root._ = _;            /**       * 检测是否数组       * 返回:true表示数组,false表示非数组       */      _.isArray = function(obj){          return toString.call(obj) === '[object Array]';      };            /**       * 这个没什么好说的吧,继承,直接copy的系列04的代码,不清楚的盆友可以看看系列04,继承源码分析       * sub:子类       * sup:父类       */      _.extend = function(sub, sup) {          var F = function(){};          F.prototype = sup.prototype;          sub.prototype = new F();          sub.prototype.constructor = sub;          sub._super = sup.prototype;          if(sup.prototype.constructor == Object.prototype.constructor){              sup.prototype.constructor = sup;          }      };            // 防止与其他库冲突      _.noConflict = function() {          root._ = previousUnderscore;          return this;      };            // 版本      _.VERSION = '1.0';            // 判断CMD模块化      if (typeof define == 'function' && define.amd) {          define('underscore', [], function() {              return _;          });      }  }())

这就是模拟underscore.js的实现了,只写了一个继承的方法,一个判断数组的方法,大家可以随意扩展方法。下面的例子就在这个基础上扩展一个遍历多维数组的方法。

JS遍历多维数组

在系列01的时候,我们用reduce实现过一个二维数组的合并,这里我们封装一个多维数组的遍历实现。这是在上面模拟underscore.js的代码里的,这里就不重复的写了,只写具体实现部分,记得放到上面的代码环境里。

/**   * 遍历多维数组   * 参数1:要遍历的数组   * 参数2:回调函数   */  _.arrEach = function(arr,fn){      // 判断传入的arr是否是数组,判断fn是否为function类型      if(_.isArray(arr) && typeof fn==='function'){          // i作为计数器          var i=0,len=arr.length;          // while遍历          while(i<len){              // 这里是判断下一层级是否为数组,如果是则递归              if(_.isArray(arr[i])){                  _.arrEach(arr[i],fn);              // 否则就直接执行回调函数,使用call则是把作用于指向数组本身              }else{                  fn.call(arr,arr[i]);              }              i++;          }          // 这里是垃圾回收,          i=null;      }else{          // 这段英文是我自己写的,英文不好请见谅!^_^          throw new Error('the first arguments must be Array and callback must be function');      }  };

测试代码,如下:

var iArr = [1,[2,[3,[4,5,[6]]]]];  _.arrEach(iArr,function(i){      alert(i);    // 返回1,2,3,4,5,6  })

这就是模拟多维数组的实现了,这个我也用在生产环境里了,大家可以根据项目需要自己扩展,这样可以避免冗余,性能更高,尤其移动端优化。

这一回,主要聊了链式调用,模拟了jQuery,尤其是underscore.js,希望大家能喜欢这次代码分享。下一回,聊一聊JS的策略模式。

sf.gg好像开通不了新专栏啊,写了一个Vue.js系列,没办法开通耶~

客观看完点个赞,推荐推荐呗,嘿嘿~~

注:此系飞狐原创,转载请注明出处

</div>

来自: http://segmentfault.com/a/1190000004270004