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

posted @ 2013-09-12 17:00  hongdada  阅读(243)  评论(0编辑  收藏  举报