Skip to content

Instantly share code, notes, and snippets.

@hevi1991
Last active April 9, 2024 06:28
Show Gist options
  • Save hevi1991/3dcee40f32c1b44f254f3a11712ab78f to your computer and use it in GitHub Desktop.
Save hevi1991/3dcee40f32c1b44f254f3a11712ab78f to your computer and use it in GitHub Desktop.
JavaScript 使用代理来实现单例模式
export function singleton(clazz) {
let instance;
return new Proxy(clazz, {
construct(target, args) {
if (instance) {
return instance;
} else {
instance = new target(...args);
return instance;
}
},
});
}
import { singleton } from "./singleton.js";
class Video {
constructor(name) {
this.name = name;
}
play() {
console.log(`${this.name} is playing`);
}
}
export default singleton(Video);
import Video from "./singletonClass.js";
const v2 = new Video(`v2`);
const v = new Video(`v`);
v.play();
v2.play();
console.log(v === v2);
@hevi1991
Copy link
Author

js singleton by using Proxy

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment