var Singleton = function(name) {
this.name = name;
//一个标记,用来判断是否已将创建了该类的实例
this.instance = null;
}
// 提供了一个静态方法,用户可以直接在类上调用
Singleton.getInstance = function(name) {
// 没有实例化的时候创建一个该类的实例
if(!this.instance) {
this.instance = new Singleton(name);
}
// 已经实例化了,返回第一次实例化对象的引用
return this.instance;
}
var a = Singleton.getInstance('sven1');
var b = Singleton.getInstance('sven2');
// 指向的是唯一实例化的对象
console.log(a === b);
class Singleton {
constructor(name) {
this.name = name;
this.instance = null;
}
// 构造一个广为人知的接口,供用户对该类进行实例化
static getInstance(name) {
if(!this.instance) {
this.instance = new Singleton(name);
}
return this.instance;
}
}
<button id="loginBtn">登录</button>
const btn = document.getElementById('loginBtn');
btn.addEventListener('click', function() {
loginLayer.getInstance();
}, false);
init() {
var div = document.createElement('div');
div.classList.add('login-layer');
div.innerHTML = "我是登录浮窗";
document.body.appendChild(div);
}
class loginLayer {
constructor() {
// 判断页面是否已有浮窗的标记
this.instance = null;
this.init();
}
init() {
var div = document.createElement('div');
div.classList.add('login-layer');
div.innerHTML = "我是登录浮窗";
document.body.appendChild(div);
}
// 静态方法作为广为人知的接口
static getInstance() {
// 根据标记的状态判断是否要再添加浮窗,如果标记不为空就创建一个浮窗
if(!this.instance) {
this.instance = new loginLayer();
}
return this.instance;
}
}
.login-layer {
width: 200px;
height: 200px;
background-color: rgba(0, 0, 0, .6);
text-align: center;
line-height: 200px;
display: inline-block;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>单例实现登录弹窗</title>
<style>
.login-layer {
width: 200px;
height: 200px;
background-color: rgba(0, 0, 0, .6);
text-align: center;
line-height: 200px;
display: inline-block;
}
</style>
</head>
<body>
<button id="loginBtn">登录</button>
<script>
const btn = document.getElementById('loginBtn');
btn.addEventListener('click', function() {
loginLayer.getInstance();
}, false);
class loginLayer {
constructor() {
this.instance = null;
this.init();
}
init() {
var div = document.createElement('div');
div.classList.add('login-layer');
div.innerHTML = "我是登录浮窗";
document.body.appendChild(div);
}
static getInstance() {
if(!this.instance) {
this.instance = new loginLayer();
}
return this.instance;
}
}
</script>
</body>
</html>
机械节能产品生产企业官网模板...
大气智能家居家具装修装饰类企业通用网站模板...
礼品公司网站模板
宽屏简约大气婚纱摄影影楼模板...
蓝白WAP手机综合医院类整站源码(独立后台)...苏ICP备2024110244号-2 苏公网安备32050702011978号 增值电信业务经营许可证编号:苏B2-20251499 | Copyright 2018 - 2025 源码网商城 (www.ymwmall.com) 版权所有