JS 设计模式

单例模式^ob_scope_closure

单例模式避免了重复实例化带来的内存开销。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
// 单例模式
function Singleton() {
this.data = "singleton";
}

Singleton.getInstance = (function () {
var instance;

return function () {
if (instance) {
return instance;
} else {
instance = new Singleton();
return instance;
}
};
})();

var sa = Singleton.getInstance();
var sb = Singleton.getInstance();
console.log(sa === sb); // true
console.log(sa.data); // 'singleton'

References

  1. Learning JavaScript Design Patterns
下一篇