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.

Revisions

  1. hevi1991 revised this gist Apr 9, 2024. No changes.
  2. hevi1991 revised this gist Oct 30, 2023. 2 changed files with 1 addition and 1 deletion.
    File renamed without changes.
    2 changes: 1 addition & 1 deletion test.js
    Original file line number Diff line number Diff line change
    @@ -1,4 +1,4 @@
    import Video from "./exampleClass.js";
    import Video from "./singletonClass.js";

    const v2 = new Video(`v2`);
    const v = new Video(`v`);
  3. hevi1991 created this gist Oct 30, 2023.
    13 changes: 13 additions & 0 deletions exampleClass
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,13 @@
    import { singleton } from "./singleton.js";

    class Video {
    constructor(name) {
    this.name = name;
    }

    play() {
    console.log(`${this.name} is playing`);
    }
    }

    export default singleton(Video);
    14 changes: 14 additions & 0 deletions singleton.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,14 @@
    export function singleton(clazz) {
    let instance;

    return new Proxy(clazz, {
    construct(target, args) {
    if (instance) {
    return instance;
    } else {
    instance = new target(...args);
    return instance;
    }
    },
    });
    }
    8 changes: 8 additions & 0 deletions test.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,8 @@
    import Video from "./exampleClass.js";

    const v2 = new Video(`v2`);
    const v = new Video(`v`);
    v.play();
    v2.play();

    console.log(v === v2);