单例模式的使用--创建登陆弹窗

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>单例模式</title>
  </head>
  <body>
    <button id="btn">登陆</button>
    <script>
      /* let createLayer = (function () {
        let div = null;
        return function () {
          // 第一次不存在则创建div
          if (!div) {
            div = document.createElement("div");
            div.innerHTML = "我说新创建的div";
            div.style.display = "none";
            document.body.append(div);
          }
          return div;
        };
      })();

      document.getElementById("btn").onclick = function () {
        let login_layer = createLayer();
        login_layer.style.display = "block";
      }; */

      //   单一职责 各自做各的事情
      let getSingle = function (fn) {
        let el = null;
        return function () {
          if (!el) {
            el = fn();
          }
          return el;
        };
      };

      let createloginLayer = function () {
        let div = document.createElement("div");
        div.innerHTML = "我说新创建弹窗";
        div.style.display = "none";
        document.body.append(div);

        return div;
      };

      let createSingleLayer = getSingle(createloginLayer);

      document.getElementById("btn").onclick = function () {
        let login_layer = createSingleLayer();
        login_layer.style.display = "block";
      };
    </script>
  </body>
</html>

 

posted @ 2022-04-03 22:36  前端那点事  阅读(92)  评论(0编辑  收藏  举报