javascript singleton question

前端 未结 10 2065
闹比i
闹比i 2020-12-12 20:08

I just read a few threads on the discussion of singleton design in javascript. I\'m 100% new to the Design Pattern stuff but as I see since a Singleton by definition won\'t

10条回答
  •  旧时难觅i
    2020-12-12 20:16

    The point of using the "pseudo constructor" is that it creates a new variable scope. You can declare local variables inside the function that are available inside any nested functions but not from the global scope.

    There are actually two ways of doing it. You can call the function with new like in your example, or just call the function directly. There are slight differences in how you would write the code, but they are essentially equivalent.

    Your second example could be written like this:

    var singleton = new function () {
        var privateVariable = 42; // This can be accessed by dothis and dothat
    
        this.dothis = function () {
            return privateVariable;
        };
    
        this.dothat = function () {};
    }; // Parentheses are allowed, but not necessary unless you are passing parameters
    

    or

    var singleton = (function () {
        var privateVariable = 42; // This can be accessed by dothis and dothat
    
        return {
            dothis: function () {
                return privateVariable;
            },
    
            dothat: function () {}
        };
    })(); // Parentheses are required here since we are calling the function
    

    You could also pass arguments to either function (you would need to add parentheses to the first example).

提交回复
热议问题