声明对象以在单个函数中重复使用的范围

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

本文关键字:范围 对象 单个 函数 声明      更新时间:2023-09-26

我不知道以下哪种方法是声明该对象的最有效/最佳实践方法。

在函数内部,我正在重用,但我认为这意味着每次调用时都会声明它

function mapVals(ele){
  var myObj = {
    "chkOne" : "HV1",
    "chkTwo" : "HV2",
    "chkThree" : "HV3"
  }
  var thisVal = myObj[ele.id];
  //Other code
}

在函数之外,但它正在污染全局命名空间

var myObj = {
  "chkOne" : "HV1",
  "chkTwo" : "HV2",
  "chkThree" : "HV3"
}
function mapVals(ele){      
  var thisVal = myObj[ele.id];
  //Other code
}

或者可能是一种创建临时作用域的封装技术?我知道语法,但以前没用过。

(function(){
  var myObj = {
     "chkOne" : "HV1",
     "chkTwo" : "HV2",
     "chkThree" : "HV3"
   }
   function mapVals(ele){      
      var thisVal = myObj[ele.id];
      //Other code
   }
})();

或者还有什么我没有考虑过的?

第三个是您提供的三个中最"安全"的,但它几乎没有什么用处,因为在您最初调用它之后,它内部的对象是不可访问的。

根据您想要做的事情的复杂性,简单的模块模式可能是最佳选择:

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

这允许您将代码"密封"在闭包中,其中myObj只定义一次,还可以导出方法来访问应用程序中的myObj(或模块中声明的其他变量)。这是对闭包力量的一个小小的尝试。

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