JavaScript approach to create a singleton or save a link to a variable

Sometimes such methods are used to keep a reference to variables or create a singleton. Thus, we will call createVariable only once. What are the pros and cons of this approach?

function createVariable() {
    // usually here may be some long asynchronous task
    // 
    return true;
}

function useVariable() {
    if(!useVariable.someVar) {
        useVariable.someVar = createVariable();
    }

    // do something with useVariable.someVar 
}

// we will call useVariable several times. 
// The idea is to call createVariable 
// one time only. 
useVariable();
useVariable();
useVariable();

I am grateful to all the ideas and recommendations. I do not want to create a singleton. I just want to keep the link variable at the function level. Without pollute the global scale.

+4
source share
2 answers

What are the pros and cons of this approach?

The approach is fine, although I doubt its necessity as a higher level design issue.

There are several problems in the implementation:

  • someVar false, , . , , if(!useVariable.hasOwnProperty("someVar")) {, if(!useVariable.someVar) {.

    false 0, "", NaN, undefined, null , , false. ( "".)

  • , (name, length), , ( , ). , name, length, call .., , , , createVariable ( createVariable). , - ( , , , ), ES2015 +, a Map.

, " " ( , ). , :

(function() {
    var someVar = createSomeVar();

    // My other code here
})();

someVar - .

+2

( http://www.dofactory.com/javascript/singleton-design-pattern):

var Singleton = (function () {
    var instance;

    function createInstance() {
        var object = new Object("I am the instance");
        return object;
    }

    return {
        getInstance: function () {
            if (!instance) {
                instance = createInstance();
            }
            return instance;
        }
    };
})();

:

var instance1 = Singleton.getInstance();
var instance2 = Singleton.getInstance();

//You can see here that they are indeed the same instance
alert("Same instance? " + (instance1 === instance2));  

: Google : http://dofactory.com/javascript/singleton-design-pattern

0

Source: https://habr.com/ru/post/1618439/


All Articles