class单例模式

2021-01-22  本文已影响0人  WWWWWWWWWWWWWWM

创建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指的是同一个实例

上一篇 下一篇

猜你喜欢

热点阅读