简体   繁体   中英

Which scope to declare an object for repeated use within a single function

I'm confused as to which of these is the most efficient / best practice ways of declaring this object.

Inside the function i'm reusing, but i presume that means it is declared everytime the function is called

function mapVals(ele){

  var myObj = {
    "chkOne" : "HV1",
    "chkTwo" : "HV2",
    "chkThree" : "HV3"
  }

  var thisVal = myObj[ele.id];
  //Other code
}

Outside the function but then it is polluting the global namespace

var myObj = {
  "chkOne" : "HV1",
  "chkTwo" : "HV2",
  "chkThree" : "HV3"
}

function mapVals(ele){      
  var thisVal = myObj[ele.id];
  //Other code
}

Or perhaps an encapsulation technique to create a temporary scope? I know the syntax but haven't used it before.

(function(){

  var myObj = {
     "chkOne" : "HV1",
     "chkTwo" : "HV2",
     "chkThree" : "HV3"
   }

   function mapVals(ele){      
      var thisVal = myObj[ele.id];
      //Other code
   }

})();

Or anything else I haven't considered?

The 3rd one is the most "secure" of the three you present, but it has little utility because the objects inside it are inaccessible after you initially invoke it.

Depending on the complexity of what you want to do, a simple module pattern may be the best choice:

var module = (function(){

  var myObj = {
     "chkOne" : "HV1",
     "chkTwo" : "HV2",
     "chkThree" : "HV3"
   };

  return {
    mapVals: function (ele){      
      var thisVal = myObj[ele.id];
   }, 
    setVal: function (prop,value) {
      myObj[prop] = value;
    },
    getVal : function (val) {
      return myObj[val];
    }
  };

})();

// we can access and modify properties of myObj within the closure
module.mapVals('chkOne');
module.setVal('foo','bar');
console.log(module.getVal('foo'));

JSbin

This allows you to "seal" your code in a closure, where myObj is only defined once, but also export methods to access myObj (or other variable declared within module) further on in your application. This is a small taste of the power of closures .

如果您不想污染全局命名空间,那么第三个选项可能是您最好的选择。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM