### 1、什么是鏈式調用
這個很容易理解,例如:
~~~
$(this).setStyle('color', 'red').show();
~~~
一般的函數調用和鏈式調用的區別:調用完方法后,`return this`返回當前調用方法的對象。
~~~
function Dog(){
this.run= function(){
alert("The dog is running....");
return this;//返回當前對象 Dog
};
this.eat= function(){
alert("After running the dog is eatting....");
return this;//返回當前對象 Dog
};
this.sleep= function(){
alert("After eatting the dog is running....");
return this;//返回當前對象 Dog
};
}
//一般的調用方式;
/* var dog1 =new Dog();
dog1.run();
dog1.eat();
dog1.sleep();*/
var dog2 = new Dog();
dog2.run().eat().sleep();
~~~
### 2、分解鏈式調用
鏈式調用其實是兩個部分:
-
1.**操作對象**(也就是被操作的DOM元素,如上例的$(this))
-
2.**操作方法**(具體要做什么事情,如上例的setStyle和show)
如何實現操作對象與操作方法
創建一般的$函數:
~~~
function $(){
var elements = [];
for(var i= 0,len=arguments.length; i<len; i++){
var element = arguments[i];
if(typeof element==='string'){
element = document.getElementById(element);
}
if(arguments.length==1){
return element;
}
elements.push(element);
}
return elements;
}
~~~
但是,如果把這個函數改造為一個構造器,把那些元素作為數組保存在一個實例屬性中,并讓所有定義在構造器函數的prototype屬性所指對象中的方法都返回用以調用方法的那個實例的引用,那么它就具有了鏈式調用的能力。(說了這么多,就是在每個方法最后`return this;`),
我首先需要把這個`$`函數改為一個工廠方法,它負責創建支持鏈式調用的對象。這個函數應該能接受元素數組形式的參數,以便我們能夠使用與原來一樣的公用接口。這樣以來,它就具有了進行鏈式調用的能力。
改造后如下:
~~~
(function(){
function _$(els){
this.elements = [];//把那些元素作為數組保存在一個實例屬性中,
for(var i= 0, len=els.length; i<len; i++){
var element = els[i];
if(typeof element==='string'){
element = document.getElementById(element);
}
this.elements.push(element);
}
}
_$.prototype = {
each: function(fn){
for(var i= 0,len=this.elements.length; i<len; i++){
fn.call(this, this.elements[i]);
}
return this; //在每個方法的最后return this;
},
setStyle: function(prop, val){
this.each(function(el){
el.style[prop] = val;
});
return this; //在每個方法的最后return this;
},
show: function(){
var that = this;
this.each(function(el){
that.setStyle('display', 'block');
});
return this; //在每個方法的最后return this;
},
addEvent: function(type, fn){
var add = function(el){
if(window.addEventListener){
el.addEventListener(type, fn, false);
}else if(window.attachEvent){
el.addEvent('on'+type, fn);
}
};
this.each(function(el){
add(el);
});
return this; //在每個方法的最后return this;
}
}
window.$ = function(){
return new _$(arguments);
}
})();
~~~
在最后return this,這就將調用方法的對象傳給調用鏈上的下一個方法。
### 3、模擬jquery底層鏈式編程
~~~
// 塊級作用域
//特點1 程序啟動的時候 里面的代碼直接執行了
//特點2 內部的成員變量 外部無法去訪問 (除了不加var修飾的變量)
(function(window , undefined){
// $ 最常用的對象 返回給外界 大型程序開發 一般使用'_'作為私用的對象(規范)
function _$(arguments){
//實現代碼...這里僅實現ID選擇器
// 正則表達式匹配id選擇器
var idselector = /#\w+/ ;
this.dom ; // 此屬性 接受所得到的元素
// 如果匹配成功 則接受dom元素 arguments[0] = '#inp'
if(idselector.test(arguments[0])){
this.dom = document.getElementById(arguments[0].substring(1));
} else {
throw new Error(' arguments is error !');
}
};
// 在Function類上擴展一個可以實現鏈式編程的方法
Function.prototype.method = function(methodName , fn){
this.prototype[methodName] = fn ;
return this ; //鏈式編程的關鍵
}
// 在_$的原型對象上 加一些公共的方法
_$.prototype = {
constructor : _$ ,
addEvent:function(type,fn){
// 給你的得到的元素 注冊事件
if(window.addEventListener){// FF
this.dom.addEventListener(type , fn);
} else if (window.attachEvent){// IE
this.dom.attachEvent('on'+type , fn);
}
return this ;
},
setStyle:function(prop , val){
this.dom.style[prop] = val ;
return this ;
}
};
// window 上先注冊一個全局變量 與外界產生關系
window.$ = _$ ;
// 寫一個準備的方法
_$.onReady = function(fn){
// 1 實例化出來_$對象 真正的注冊到window上
window.$ = function(){
return new _$(arguments);
};
// 2 執行傳入進來的代碼
fn();
// 3 實現鏈式編程
_$.method('addEvent',function(){
// nothing to do
}).method('setStyle',function(){
// nothing to do
});
};
})(window); // 程序的入口 window傳入作用域中
$.onReady(function(){
var inp = $('#inp');
//alert(inp.dom.nodeName);
//alert($('#inp'));
inp.addEvent('click',function(){
alert('我被點擊了!');
}).setStyle('backgroundColor' , 'red');
});
~~~
### 4、使用回調函數從支持鏈式調用的方法獲取數據
鏈式調用很適合于賦值器方法,但對于取值器方法,就不方便了,因為每個方法返回的都是this啊。
不過,變通的方法還是有的,那就是回調函數。
**未使用回調函數時**
~~~
//without callback
window.API = window.API || function(){
var name = 'JChen';
this.setName = function(newName){
name = newName;
return this;
};
this.getName = function(){
return name;
};
};
var o = new API();
console.log(o.getName());
console.log(o.setName('Haha').getName());
~~~
**使用回調函數時**
~~~
//with callback
window.API2 = window.API2 || function(){
var name = 'JChen';
this.setName = function(newName){
name = newName;
return this;
};
this.getName = function(callback){
callback.call(this, name);
return this;
};
};
var o2 = new API2();
o2.getName(console.log).setName('Hehe').getName(console.log);
~~~
在使用回調函數時候callback.call(this, name)在一般情況下是沒問題的,但是,這個例子偏偏用到了console.log,那么就有問題了。原因是console的this是指向console而不是winodw。
這個問題也很好解決。如下:
~~~
//with callback
window.API2 = window.API2 || function(){
var name = 'JChen';
this.setName = function(newName){
name = newName;
return this;
};
this.getName = function(callback){
callback.call(this, name);
return this;
};
};
var o2 = new API2();
var log = function(para){
console.log(para);
};
o2.getName(log).setName('Hehe').getName(log);
~~~
### 5、總結
鏈式調用這種風格有助于簡化代碼的編寫工作,讓代碼更加簡潔、易讀,同時也避免多次重復使用一個對象變量。