单例模式指的是只能被实例化一次。

推荐阅读:

http://blog.mgechev.com/2014/04/16/singleton-in-javascript/

比较通用的一种Singleton模式

var mySingleton = (function () {
// Instance stores a reference to the Singleton
var instance;
function init() {
// Singleton
// Private methods and variables
function privateMethod(){
console.log( "I am private" );
}
var privateVariable = "Im also private";
var privateRandomNumber = Math.random();
return {
// Public methods and variables
publicMethod: function () {
console.log( "The public can see me!" );
},
publicProperty: "I am also public",
getRandomNumber: function() {
return privateRandomNumber;
}
};
};
return {
// Get the Singleton instance if one exists
// or create one if it doesn't
getInstance: function () {
if ( !instance ) {
instance = init();
}
return instance;
}
};
})();
var singleA = mySingleton.getInstance();
var singleB = mySingleton.getInstance();
console.log( singleA === singleB); // true

这种写法的好处有

1.只能实例化一次

2.可以存在私有函数

3.变量不可访问,不容易被修改。

最新文章

  1. 0x00linux32位汇编初入--前期准备
  2. python 线程编程
  3. php——用for循环打印半金字塔、金字塔、正方形、倒金字塔、菱形、空心图形等
  4. Thrift 个人实战--Thrift 网络服务模型
  5. POI对Excel
  6. J2EE 第二阶段项目(八)
  7. Hadoop中的辅助类ToolRunner和Configured的用法详解
  8. Oracle DB 使用调度程序自动执行任务
  9. AutoCAD.NET二次开发:创建自定义菜单(COM)
  10. Android版本控制系统及其间的差异
  11. Eclipse servlet和jsp编写
  12. html5学习(一) video字段
  13. 029_mount bind挂载
  14. Torchvision 源码安装[Ubuntu]
  15. freckles
  16. TCP_NODELAY算法使用事项
  17. Python oct() 函数
  18. PHP MemCached高级缓存配置图文教程
  19. gopherjs
  20. 由于link顺序错误导致的undefined reference

热门文章

  1. lua 类继承和实现
  2. PCL库配置出现的问题(WIN10+VS2013)
  3. 常用SQL Server分页方式
  4. C#面试题总结——程序设计基础
  5. WindowsAPI一日一练
  6. 不规则三角网 Delaunay——TIN
  7. Ecsotre 参考
  8. SQL Server 创建索引的 5 种方法
  9. 利用Azure Backup备份和恢复虚拟机(2)
  10. nginx的请求接收流程(二)