使用代理实现单例
作者:xie392地址:https://v.douyin.com/ie9K97AL/更新时间:2024-12-21
案例代码
1class MyVideo {2constructor(a, b) {3this.a = a;4this.b = b;5}67sayHello() {8console.log("hello");9}10}1112function isSame(value1, value2) {13if (value1.length !== value2.length) {14return false;15}1617for (let i = 0; i < value1.length; i++) {18if (value1[i] !== value2[i]) {19return false;20}21}2223return true;24}2526function singaleton(className) {27let ins, parameters;28return new Proxy(className, {29construct(target, args) {30if (!ins) {31ins = new target(target, ...args);32parameters = args;33}34if (!isSame(parameters, args)) {35throw new Error("参数不一致");36}37return ins;38},39});40}4142const Video = singaleton(MyVideo);4344const v1 = new Video();45const v2 = new Video();4647console.log("v1 === v2:", v1 === v2);
输出结果:
1v1 === v2: true
目录