js实现单例模式

来源:互联网 发布:安卓钣金展开软件 编辑:程序博客网 时间:2024/05/30 13:42
//结合闭包、原型
(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());
0 0