利用proxy创建单例唯一模式

class MyVideo {
    constructor(){

    }
 }
 function singleton(className){
    let ins = null 
    const proxy = new Proxy(className,{
        construct(target,args){
            console.log(11111)
            if(!ins){
                ins = Reflect.construct(target,args)
            }
            return ins
        }
    })
    className.prototype.constructor = proxy
    return proxy
 }

 const myVideoSingleton = singleton(MyVideo)
//  export default new MyVideo();
let vdo1 = new myVideoSingleton()
let vdo2 = new myVideoSingleton()
console.log(vdo1 === vdo2)

  

posted @ 2024-12-14 17:19  国服第一李师师  阅读(13)  评论(0)    收藏  举报