欢迎您访问 最编程 本站为您分享编程语言代码,编程技术文章!
您现在的位置是: 首页

JS 设计模式 (I) 单例模式

最编程 2024-07-21 11:44:22
...
<!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>