如何在嵌套结构中声明变量

How to declare a variable inside nested structure?

本文关键字:声明 变量 结构 嵌套      更新时间:2023-09-26

假设我有一个嵌套结构,其中包含JavaScript中的对象和函数,如下所示:

this.x = {
   f1: function() {
   },
   f2: function() {
   },
   nested: {
      f3: function() {
      },
      f4: function() {
      }
   }
}

假设我想要声明一个只有函数f3和f4才知道的变量。在哪里以及如何声明这个变量?

从您的结构来看,嵌套应该是一个对象,对吗?您可以使用所谓的自执行函数。

x = {
  f1: function() {
      //Does not have access to abc
  }, 
  f2: function() {
      //Does not have access to abc
  }
};
x.nested = (function() {
  var abc = '123';
  //Must return an object here to keep nested as an object
  return {
    f3: function() {
      console.log(abc);
    }, 
    f4: function() {
        console.log(abc);
    }
  };
})();

包含在x.nested中的函数将能够访问abc,就好像它是彼此共享的全局变量一样,而f1f2则不能。

你能做这样的事情吗?

this.x = {
   f1: function() {
   },
   f2: function() {
   },
   nested: (function() {
      var nested_var;
      return {
          f3: function() {
              // nested_var in scope here
          },
          f4: function() {
              // and here, shared between f3 and f4
          }
      }; 
   })();
}

只需在函数范围内声明变量,它将仅对该函数可见。示例

function f3() {
  var nestedVar = 3;
}
var notNested = nestedVar;   // this will not work

也许是这样的:

this.x = {
   f1: function() {
   },
   f2: function() {
   },
   nested: (function(){
     var priv=0;
     return {
       f3:function(){priv++;},
       f4:function(){return priv;}
     };
   })()
};

(function(){/*code*/})()部分是一个匿名函数,然后执行(您有时会在用户脚本和bookmarklet中看到这些)。