JS設計模式——6.方法的鏈式調用


什么是鏈式調用

這個很容易理解,例如:

$(this).setStyle('color', 'red').show();

分解鏈式調用

鏈式調用其實是兩個部分:

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,這就將調用方法的對象傳給調用鏈上的下一個方法。

使用回調函數從支持鏈式調用的方法獲取數據

鏈式調用很適合於賦值器方法,但對於取值器方法,就不方便了,因為每個方法返回的都是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);

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM