單體模式封裝

weixin_34308389發表於2016-09-13
<!DOCTYPE html>
<html>

    <head>
        <meta charset="UTF-8">
        <title></title>
        <script type="text/javascript">
            var Singalton = function(name) {
                this.name = name;
            }
            Singalton.prototype.getName = function() {
                return this.name;
            }
            var getInstance = (function() {
                //建立這個變數只執行一次(自呼叫只執行一次)
                var instance = null;
                //向外部返回一個由getInstance儲存的函式
                return function(name) {
                // 在函式內部呼叫了區域性變數,並把該函式返回出去,則這個變數會變成全域性變數(閉包的概念)
                    if(!instance) {
                        instance = new Singalton(name);
                    }
                    return instance;
                }
            })();
            var a = getInstance('a');
            var b = getInstance('b');
            console.log(a.getName());
            console.log(b.getName());
        </script>
    </head>

    <body>
    </body>

</html>

相關文章