Simplest/Cleanest way to implement singleton in JavaScript?

后端 未结 30 1060
名媛妹妹
名媛妹妹 2020-11-22 05:17

What is the simplest/cleanest way to implement singleton pattern in JavaScript?

30条回答
  •  一向
    一向 (楼主)
    2020-11-22 05:44

    I needed several singletons with:

    • lazy initialisation
    • initial parameters

    and so this was what I came up with:

    createSingleton ('a', 'add', [1, 2]);
    console.log(a);
    
    function createSingleton (name, construct, args) {
        window[name] = {};
        window[construct].apply(window[name], args);
        window[construct] = null;
    }
    
    function add (a, b) {
        this.a = a;
        this.b = b;
        this.sum = a + b;
    }
    
    • args must be Array for this to work so if you have empty variables, just pass in []

    • I used window object in the function but I could have passed in a parameter to create my own scope

    • name and construct parameters are only String for window[] to work but with some simple type-checking, window.name and window.construct are also possible.

提交回复
热议问题