js单例模式

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
//单例模式1
var mySingleton = {
name:’songjiang’,
age:’45’,
run:function(){
//
}
}

//单例模式2,

var mySingleton2 = function(){
//私有
var instantiated;
var privateVariable = ‘v’;
function walk(){

};
//公有
if(!instantiated){
instantiated = {
publicV : ‘pv’,
publicMethod:function(){
console.log(privateVariable);
}
}
}
return instantiated;
}

//单例模式3 只有当使用时才会初始化

var mySingleton3 = (function(){
var instantiated ;

//主体
function init(){
return{
publicMethod:function(){

},
publicV:’v’,
}
}

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