1. 程式人生 > >初識javascript程式設計模式

初識javascript程式設計模式

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>程式設計模式</title>
    <style>
        body {
            width: 100%;
            height: 1000px;
        }
    </style>
</head>
<body>
這是body的內容!
<script>
  //一、行為隔離
    /*
    * 1.1、內容(html)
    * 1.2、外觀(css)
    * 1.3、行為(javascript)
    *1.4、準則:
    *    1.4.1、儘量避免在HTML標籤中使用樣式類的屬性。
    *    1.4.2、不要使用與外觀有關的HTML標籤,例如<font>
    *    1.4.3、儘量根據語義需要選擇標籤,而不是去考慮瀏覽器會如何繪製它們。
    *
    *二、名稱空間
    * 2.1、將物件用做名稱空間
    *
    *
    *
    *
    * */
    var MYAPP = MYAPP || {};
    MYAPP.event = {};
    MYAPP.event = {
        addListener: function(el,type,fn){
                console.log("自定義監聽……");
        },
        remvoeListener: function(el,type,fn){
                console.log("移除自定義監聽");
        },
        getEvent: function(){
            console.log("得到事件型別");
        }
    }

    /*
    * 2.2、名稱空間中的構造器應用
    *
    * */
    MYAPP.dom = {};
    MYAPP.dom.Element = function(type, prop){
        var tmp = document.createElement(type);
        for(var i in prop){
            tmp.setAttribute(i,prop[i]);
        }
        return tmp;
    }
    /*
    *
    * 三、namespace()方法???
    * */
    var app = {};
    app.namespace = function(name){
        var parts = name.split('.');
        var current = app;
        var i = 0,
            len = parts.length;
        for(;i < len; i++){
            if(!current[parts[i]]){
                current[parts[i]] = {};
            }
            current = current[parts[i]];
        }
    };
    app.namespace('dom.style.css');
    console.log(app);
    /*
    * 四、初始化分支
    *  在載入指令碼時,在模組初始化的過程中就將部分程式碼進行分支處理。
    *  利用javascript程式碼可以動態定義的特性,我們可以為不同的瀏覽器定製不同的實現方法。
    * */
    //事件繫結
    var branch = {};
    branch.event = {
        addListener: null,
        removeListener: null
    };

    if(typeof window.addEventListener === "function"){
        branch.event.addListener = function(el,type,fn){
            el.addEventListener(type, fn, false);
        }
    }else if(typeof document.attachEvent === 'function'){
        branch.event.addListener = function(el, type ,fn){
            el.attachEvent('on' + type, fn);
        }
    }
    else {
        branch.event.addListener = function(el, type , fn){
            el['on' + type] = fn;
        }
    }

    if(typeof window.removeListener === "function"){

        branch.event.removeListener = function(el, type, fn){
            el.removeEventListener(type,fn,false);
        };

    }
    else if(typeof document.detachEvent){

        branch.event.removeListener = function(el, type, fn){
            el.attachEvent('on' + type, fn);
        };

    }
    else {
            el['on' + type] = null;
    }
/*    window.onload = function(){

        branch.event.addListener(document.body,'click',function(e){
            alert(e.target);
        });

    };*/
    /*
    * 五、延遲定義???
    *
    *
    * */
    var i=0;
    var deffer = {};
    deffer.myevent = {
        addListener: function(el, type, fn){
            debugger;
            console.log("我被呼叫了"+ (++i)+"次");
            if(typeof el.addEventListener === 'function'){
                deffer.myevent.addListener = function(el, type, fn){
                    el.addEventListener(type, fn, false);
                };
            }
            else if (typeof el.attachEvent === 'function'){
                deffer.myevent.addListener = function(el, type, fn){
                    el.attachEvent('on' + type, fn);
                }
            }
            else {
                deffer.myevent.addListener = function(el, type, fn){
                    el['on' + type] = fn;
                }
            }
                deffer.myevent.addListener(el, type, fn);
        }
    };
    deffer.myevent.addListener(document.body,'click',function(e){
        alert(e.target);
    });
    deffer.myevent.addListener(document.body,'click',function(e){
        alert(e.target);
    });

    /*
    * 六、配置物件
    * 該模式適合於有很多個引數的函式或方法。
    * 用單個物件來替代多個引數有以下幾點優勢:
    *   6.1、不用考慮引數的順序。
    *   6.2、可以跳過某些引數的設定。
    *   6.3、函式的擴充套件性更強,可以適應將來的擴充套件需要。
    *   6.4、程式碼的可讀性更好,因為在程式碼中我們看到的是配置的屬性名稱。
    * */
    var butApp = {};
    butApp.dom = {};
    butApp.dom.Button = function(text, conf){
           var type = conf.type||'submit';
           var font = conf.font|| '微軟雅黑';
           var button = document.createElement('input');
           button.type = type || 'submit';
           button.value = text;
           return button;
    };
    var config = {
        font: 'Arial, Verdana, sans-serif',
        color: 'white'
    };
    document.body.appendChild(new butApp.dom.Button('這是我建立的按鈕',config));
    /*
    * 七、私有屬性和方法
    *
    * */
    var private = {};
    private.dom = {};
    private.dom.Button = function(text, conf){
            var styles = {
                font: 'Verdana',
                border: '1px solid black',
                color: 'black',
                background: 'gray'
            };
            function setStyles() {
                for(let i in styles){
                    b.style[i] = conf[i] || styles[i];
                }
            }
            conf = conf || {};
            var b = document.createElement('input');
            b.type = conf['type']||'submit';
            b.value = text;
            setStyles();
            return b;
    }
    /*
    * 八、自執行函式
    * 保證全域性空間不被汙染,把程式碼封裝在一個匿名函式中並立刻自行呼叫。
    * 該函式中的所有變數都是區域性的,並在函式返回時被銷燬(前提是它們不屬於閉包)
    * */

    /*
    * 自執行方法也可以用於建立和返回物件
    *
    * */
    var iif = {};
    iif.dom = function(){
        function _private(){
            //...
        }
        return {
            getStyle: function(el, prop){
                 console.log('getStyle');
                 _private();
            },
            setStyle: function(el,prop,value){
                console.log('setStyle');
            }
        }
    }();
    /*
    * 九、鏈式呼叫
    *  使用方法返回的例項來呼叫其他方法,這就是所謂的鏈式呼叫。
    * */
    var chain = {};
        chain.dom = {};

    chain.dom.element = function(element){

        var elem = document.createElement(element);

            this.elem = elem;
            this.setText = function(text){

                elem.innerHTML = text;
                return this;
            };

            this.setStyle = function(styles){
                var argNum = arguments.length;
                if(argNum == 2){
                    if(typeof arguments[0] === "string"&&typeof arguments[1]==="string"){
                        elem.style[arguments[0]] = arguments[1];
                    }
                }
                if(typeof styles === "object"){
                    for(let i in styles){
                        elem.style[i] = styles[i];
                    }
                }
                    return this;
            };

    };

    var spans = new chain.dom.element('div');
        spans.setText('hello').setStyle('color', 'red').setStyle('font', 'Verdana');
        document.body.appendChild(spans.elem);
    //十、JSON
 var json = {
        'name':'Stoyan',
      'family': 'Stefanov',
       'books': ['php','java','html5']
    };
    /*

     <?xml version='1.1' encoding = 'iso-8859-1'?>
     <response>
        <name>Stoyan</name>
        <family>Stefanov</family>
        <books>
            <book>php</book>
            <book>java</book>
            <book>html5</book>
        </books>
     </response>
     */
    // var obj = eval('('+ xhr.responseText +')');
     alert(obj.name);
     alert(json.books[2]);
</script>
</body>
</html>