导航

js实现单例模式

Posted on 2014-11-13 23:08  酷鱼影子  阅读(128)  评论(0编辑  收藏  举报
//结合闭包、原型
(function(){
function Person(){

}
Person.prototype.id = 12;
Person.prototype.age = 23;
Person.prototype.name = "李项京";
Person.prototype.method = function(){
return "sdf";
};
Person.prototype["person"] =new Person();
function getInstance(){
return Person.prototype.person;
}
window.getInstance = getInstance;
})(window);
alert(window.getInstance().name); //三次调用,只执行一次new Person,说明已经是单例了
alert(window.getInstance().id);
alert(window.getInstance().age);
alert(window.getInstance().method());