- 单例模式指的是当用class在生成实例的时候,只会生成一个实例,这个在登录注册弹框,或者WebSocket方面用的比较多
创建class构造函数
// ./socket_service.js
export default class SocketService {
/**
* 单例
*/
static instance = null;
static getInstance() {
if (!this.instance) {
this.instance = new SocketService()
};
return this.instance;
};
ws = null;
// 定义连接
connect() {
if (!window.WebSocket) {
alert("您的浏览器不支持websocket");
return;
};
this.ws = new WebSocket('ws://localhost:9998');
}
}
生成唯一的class 实例
import SocketService from '@/utils/socket_service';
SocketService.getInstance() 生成class实例
//举例子
let a = SocketService.getInstance() ;
let b = SocketService.getInstance() ;
console.log(a === b) //true 说明a和b指的是同一个实例
网友评论