Search code examples
javascriptobject-literal

js using object literals for var replacement


for the longest time now i've used object literals to replace multiple var statements within my code. here's a typical example:

(function(){
  var replaceVars = {};
  function x(){
    replaceVars.num=886;
}
  function y(){
    x();
    replaceVars.cal = replaceVars.num*99;
    return replaceVars.cal;
  }
})();

so my question is: is there anything wrong with this? i mean the up sides i can see are that: 1) there is only one var statement within the whole of my code. 2) within the closure all children can access it(which means replaceVars properties become global within the scope of the closure. it's like making a global-like child object (the closure) within the true global object(the window) 3) i can pre-define properties that are ready to go immediately:

var replaceVars={ something1:"some value", something2:"some other value" }

so can anyone think of any downsides to my way of doing things?


Solution

  • I don't think there's anything wrong with using a container object. Though, I'd make a habit with it of declaring the variables needed for the related code:

    var replaceVars = {
        num: null,
        cal: null
    };
    

    But, then again, this works as well:

    (function () {
      var num, cal;
    
      function x(){
        num = 886;
      }
    
      function y(){
        x();
        cal = num * 99;
        return cal;
      }
    })();