Is it possible to simulate constants in Javascript using closures?

后端 未结 4 362
余生分开走
余生分开走 2021-01-27 09:24

Is it possible to simulate constants in Javascript using closures? If so, can you please furnish me with an example?

4条回答
  •  长情又很酷
    2021-01-27 09:53

    To declare :

    function globals(){
        const x1="something";
        const x2="otherthing";
    
        return{
          getX1=function(){
            return x1;
          },
          getX2=function(){
            return x2;
          }
        }
     }
    
    var globalConstants=globals();
    

    To access :

    globalConstants.getX1();
    

提交回复
热议问题