聽飛狐聊JavaScript設計模式系列14
本回內容介紹
上一回,聊了聊狀態模式(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系列,沒辦法開通耶~
客觀看完點個贊,推薦推薦唄,嘿嘿~~