<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
    <script type="text/javascript">
      /*
      通过一个匿名函数自执行运行,动态创建返回对象,通过函数作用域来形成私有变量的一种技巧
模拟单例模式
    */ var mySingleton = (function () { //实例保持了Singleton的一个引用 var instance; function init() { //Singleton //私有方法和变量 function privateMethod() { console.log("I am private"); } var privateVariable = "Im also privete"; var privaeRandomNumber = Math.random; return { //公有方法和变量 publicMethod: function () { }, publicPropterty: "I am also public", getRandomNumber: function () { return privaeRandomNumber; } } }; return { //获取Singleton的实例,如果存在就返回,不存在就创建新的实例 getInstance: function () { if (!instance) { instance = init(); } return instance; } } })() </script> </head> <body> </body> </html>

 

相关文章:

  • 2022-12-23
  • 2021-07-03
  • 2022-02-08
  • 2022-12-23
  • 2021-10-03
  • 2022-01-03
  • 2022-03-10
  • 2021-12-11
猜你喜欢
  • 2022-12-23
  • 2021-05-23
  • 2022-12-23
  • 2021-09-21
  • 2021-07-15
  • 2021-10-29
相关资源
相似解决方案