js简单实现单例模式

var Singleton = (function() {

            var instantiated;
            function init() {
                return {
                    publicMethod: function() {
                        console.log('hello world');
                    },
                    publicProperty: 'test'
                };
            }

            return{
                getInstance:function() {
                    if (!instantiated) {
                        instantiated = init();
                    }
                    return instantiated;
                }
            };


        })();
        Singleton.getInstance().publicMethod();

百度已收录
分享