0
点赞
收藏
分享

微信扫一扫

Skip List:平衡搜索效率与数据结构复杂性

小_北_爸 2024-07-24 阅读 27

本文建立在已有JS面向对象基础的前提下,若无,请移步以下博客先行了解

JS面向对象(一)类与对象写法

单例模式在开发中广泛应用,例如管理全局状态、配置信息、日志记录器等场景,确保整个应用程序中某个类只有一个实例是非常有用的

index.html

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body></body>
  <script>
    class LoginForm {
      constructor() {
        this.state = "hide";
      }
      show() {
        if (this.state === "show") {
          alert("已经显示");
          return;
        }
        this.state = "show";
        console.log("登录框显示成功");
      }
      hide() {
        if (this.state === "hide") {
          alert("已经隐藏");
          return;
        }
        this.state = "hide";
        console.log("登录框隐藏成功");
      }
    }
    LoginForm.getInstance = (function () {
      let instance; //因为是闭包,这个标识可以存储在函数内部,所以这里可以保证实例的唯一性
      return function () {
        if (!instance) {
          instance = new LoginForm();
        }
        return instance;
      };
    })();

    let obj1 = LoginForm.getInstance();
    obj1.show();

    let obj2 = LoginForm.getInstance();//两次获取的实例是同一个
    obj2.hide();

    console.log(obj1 === obj2);

    //这里演示一下闭包的应用
    //--------------------------------------------------
    /*
    function myTest() {
      let sum = 0;
      return function add(num) {
        sum += num;
        console.log(sum);
      };
    }
    let add = myTest();
    add(1);
    add(2);
    let add2 = myTest();
    add2(5);
    add2(6);
    */
  </script>
</html>

举报

相关推荐

0 条评论