仿jquery - zketer簡單庫

實現的功能:

1: 命名空間$, zKeter的分離
2: 無 new 構造對象
3: 選擇器的實現
4: 擴展函數的實現
5: 鏈式調用的實現
6: ready的實現 [參考文檔]
/**
 *
 * @Author zpw
 * @Describe  仿jQuery -  zKeter庫
 * @Time 2019/10/12  
 *
 */

;(function(win,undefined){

    //避免 document 之類的全局變量被其他插件修改
    var document = window.document,
        navigator = window.navigator,
        location = window.location;

           
    var zKeter,
        init,
        arr = [],
        classTools = {};


    //節省查找內存地址時間,提高效率 
    var slice = arr.slice,
        concat = arr.concat,
        push = arr.push,
        indexOf = arr.indexOf,
        toString = classTools.toString,
        hasOwn = classTools.hasOwnProperty;


    zKeter = function(selector,context){
        return new zKeter.fn.init(selector);
    };

    zKeter.fn = zKeter.prototype = {
        version : "0.1.0",
        constructor: zKeter,
        ready : function(fn){
            // Mozilla、Opera和webkit 525+內核支持DOMContentLoaded事件
            if(document.addEventListener) {
                document.addEventListener('DOMContentLoaded', function() {
                    document.removeEventListener('DOMContentLoaded',arguments.callee, false);
                    fn();
                }, false);
            } 
            //IE
            else if(document.attachEvent) {
                // 確保當頁面是在iframe中加載時,事件依舊會被安全觸發
                document.attachEvent('onreadystatechange', function() {
                    if(document.readyState == 'complete') {
                        document.detachEvent('onreadystatechange', arguments.callee);
                        fn();
                    }
                });

                // 如果是IE且頁面不在iframe中時,輪詢調用doScroll 方法檢測DOM是否加載完畢
                if(document.documentElement.doScroll && typeof window.frameElement === "undefined") {
                    try{
                        document.documentElement.doScroll('left');
                    }
                    catch(error){
                        return setTimeout(arguments.callee, 20);
                    };
                    fn();
                }
            }
            return this;
        }
    };

    init = zKeter.fn.init = function(selector) {

        var elem,
            length;

        //$(""), $(null), $(undefined), $(false)
        if(!selector){
            return this;
        }

        //判斷selector是否爲字符串
        if(typeof selector === "string"){

            //Class選擇器
            if(selector.indexOf('.') > -1){ 
                elem = document.querySelectorAll(selector);
                for(var i=0,len=elem.length;i<len;i++){
                    this[i] = elem[i];
                }
                length = len;
            }
            //ID選擇器
            else if(selector.indexOf('#') > -1){
                elem = document.querySelector(selector);
                this[0] = elem;
                length = 1;
            }
            //HTML標籤
            else{
                elem = document.querySelectorAll(selector);
                for(var i=0,len=elem.length;i<len;i++){
                    this[i] = elem[i];
                }
                length = len;
            }
        }
        //判斷selector是否爲DOMElement
        else if(selector.nodeType){
            elem =  selector;
            length = 1;
        }
        
        this.length = length;
        this.context = document;
        this.selector = selector;
        return this;
    }

    init.prototype = zKeter.fn;

    //擴展合併函數
    zKeter.extend = zKeter.fn.extend = function() {
        var key,
            target = this,
            source = arguments[0] || {};

        for (key in source) {
            if (hasOwn.call(source,key)) {
                if (typeof(source[key]) === "object") {
                    target[key] = (source[key].constructor === Array) ? [] : {};
                    arguments.callee(source[key], target[key]);
                } else {
                    target[key] = source[key];
                }
            }
        }
        return target;
    };

    //擴展靜態方法
    zKeter.extend({
      
    });

   //擴展實例方法
   zKeter.fn.extend({

   });

   window.zKeter = window.$$ = zKeter;

}(window));

分析圖:

[源碼分析圖]

測試代碼如下:

//無 new 構造對象
console.dir($$("#btn"));


//選擇器的實現
console.dir($$("#btn"));
console.dir($$(".btn"));
console.dir($$("li"));


//擴展函數的實現
zKeter.extend({
      speak : function(){
          console.log("說話")
          return this;
      },
      drink : function(){
            console.log("喝水")
            return this;
      }
});

zKeter.fn.extend({
       swimming : function(){
             console.log("游泳")
             return this;
       },
       run : function(){
             console.log("跑步")
             return this;
       }
});


//鏈式調用的實現
$$.speak().drink();
$$("#btn").swimming().run();


//ready的實現
$$(document).ready(function(){
    console.log("hello world");
});
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章