JavaScript 单例模式

1.function的静态变量

  <script type="text/javascript">
        function Universe() {
            this.name = "hongda";
            this.age = 28;
            if (Universe.instance) {
                return Universe.instance;
            }
            Universe.instance = this; 
        }
        var uni = new Universe();
        var uni2 = new Universe();
        console.log(uni === uni2);
    </script>

2.重写function的构造函数(其实就是把function覆盖)

 <script type="text/javascript">
        function Universe() {
            this.name = "hongda";
            this.age = 28;
            var instance = this;
            Universe = function () {
                return instance;
            }
        }
        var uni = new Universe();
        var uni2 = new Universe();
        console.log(uni === uni2);
    </script>

3.封装

        var Universe;
        (function () {
            var instance;
            Universe = function () {
                if (instance) {
                    return instance;
                }
                instance = this;
                this.name = "hongda";
                this.age = 28;
            };
        } ());
        var uni = new Universe();
        var uni2 = new Universe();
        console.log(uni === uni2);

http://www.cnblogs.com/TomXu/archive/2012/02/20/2352817.html

原文地址:https://www.cnblogs.com/hongdada/p/3317314.html