本回内容引见
上一回,聊了聊状况形式(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系列,没办法开通耶~
客观看完点个赞,引荐引荐呗,嘿嘿~~
注:此系飞狐原创,转载请说明出处