Conditionally initializing a constant in Javascript

前端 未结 4 1687
[愿得一人]
[愿得一人] 2020-12-15 02:42

ES6 onwards we have const.

This is not allowed:

const x; //declare first
//and then initialize it
if(condition) x = 5;
else x = 10;
         


        
4条回答
  •  生来不讨喜
    2020-12-15 03:30

    I suggest this solution with a Singleton Pattern implementation:

    var Singleton = (function () {
        var instance;
    
        function createInstance() {
            // all your logic here
            // so based on your example:
            // if(condition) return 5;
            // else return 10;
        }
    
        return {
            getInstance: function () {
                if (!instance) {
                    instance = createInstance();
                }
                return instance;
            }
        };
    })();
    
    const x = Singleton.getInstance();
    

提交回复
热议问题