javascript——单例模式

 

<!DOCTYPE html>
<html>
<head>
    <meta content="width =device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" name="viewport" />
    <meta name="apple-mobile-web-app-status-bar-style" content="black" />
    <meta name="apple-mobile-web-app-capable" content="yes" />
    <meta name="format-detection" content="telephone=no" />
    <title></title>
    <style>
        html, body { margin: 0px; padding: 0px; height: 100%; width: 100%; }
        p { margin: 0px; padding: 0px; }
        .page { width: 100%; height: 100%; }
    </style>
</head>
<body>
    <a class="single" id="single">点击</a>
    <a class="single" id="single1">点击</a>
    <script>
        //基于面向对象单例模式
        var CreateDiv = (function () {
            var instance;
            var CreateDiv = function (html) {
                if (instance) {
                    return instance;
                }
                this.html = html;
                this.init();
                return instance = this;
            }
            CreateDiv.prototype.init = function () {
                var div = document.createElement('div');
                div.innerHTML = this.html;
                document.body.appendChild(div);
            }
            return CreateDiv;
        })();
        var a = new CreateDiv('<span>测试单例0</span>');
        var b = new CreateDiv('<span>测试单例1</span>');
        console.log(a == b);

        //js面向对象
        var obj = {};

        //惰性单例模式
        var getSingle = function (fn) {
            var result;
            console.log(result);
            return function () {
                return result || (result = fn.apply(this, arguments));
            }
        }

        var bindevent = getSingle(function () {
            document.getElementById('single').onclick = function () {
                console.log('0');
            };
        });
        var bindevent1 = getSingle(function () {
            document.getElementById('single1').onclick = function () {
                console.log('1');
            };
        });

        var render = function () {
            console.log('开始渲染列表');
            bindevent();
            bindevent1();
        }
        render();
        render();
        render();
        render();
        render();
        render();

    </script>
</body>
</html>

  

posted on 2015-07-03 16:21  流浪小白鼠  阅读(124)  评论(0)    收藏  举报