js设计模式之单例模式

发布时间 2023-12-31 22:33:06作者: 光影少年
//字面量
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())