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

JS中的单例模式设计

最编程 2024-08-06 13:20:59
...
//字面量
const logi = {
   name: "贾维斯",
   password: '123456',
   method: function () {

   }
}
/**
* 闭包:
* 1. 闭包是指有权访问另一个函数作用域中的变量的函数
* 2. 创建闭包的常见方式,就是在一个函数内创建另一个函数,通过另一个函数访问这个函数的局部变量,
* 优点:
*    1、读取函数内部的变量
*    2、持久化存储
* 缺点:
*    1、不安全
*    2、不利于代码的维护和扩展
*    3、造成内存泄漏(IE)
*/
const single = (function () {
   let instance;

   function getInstance() {
       //保证对象的唯一性
       if (instance === undefined) {
           instance = new Construce();
       }
     return instance;
   }

   function Construce() {
       //生成一些代码
       return {
           name:"雷神",
           getName() {
               return this.name;
           }
       }
   }
   return {
       getInstance:getInstance
   }
})()
console.log(single.getInstance().name)
console.log(single.getInstance().getName())