单例模式
单例模式,顾名思义,只有一个实例,可以理解为多次创建,只返回一个实例。
静态属性实现单例模式
<html>
<head>
<meta charset="utf-8">
<style>
#box{
width: 100px;
height: 100px;
border: 1px solid red;
}
</style>
</head>
<body>
<input type="button" id="txt" value="点击">
<script>
function Person(){
if(!Person.instance){
Person.instance = {
name : 'ZhangSan',
age : 14,
show : function(){
var box = document.createElement('div');
box.innerHTML = this.name + ' is ' + this.age + ' years old'
box.id = 'box';
document.body.appendChild(box)
}
}
return Person.instance;
}
}
txt.onclick = function(){
var person1 = new Person();
if(person1.show){
person1.show();
}
}
</script>
</body>
</html>
不过静态属性存在在外界被修改的情况
即时函数实现单例
<html>
<head>
<meta charset="utf-8">
<style>
#box{
width: 100px;
height: 100px;
border: 1px solid red;
}
</style>
</head>
<body>
<input type="button" id="txt" value="点击">
<script>
(function (w){
var instance = null;
function Person(){
if(instance){
console.log('before',instance)
instance.show = null;
console.log('after',instance)
return instance;
}
instance = this;
this.name = 'ZhangSan';
this.age = 14;
this.show = function(){
var box = document.createElement('div');
box.innerHTML = this.name + ' is ' + this.age + ' years old'
box.id = 'box';
document.body.appendChild(box)
}
}
w.Person = Person;
})(window)
txt.onclick = function(){
var person1 = new Person();
if(person1.show){
person1.show();
}
}
</script>
</body>
</html>
这个例子运用匿名函数自运行来保存有局部变量,这样外部不可以获取这个变量,只可以获取暴漏给window的构造函数,避免了被修改。
这里使用console.log()输出了一下,判断出确实是一个实例。
惰性函数实现单例模式
暂时没有理解透彻,所以留待更新。