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

时间:2014-10-23 20:36:02

标签: javascript

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

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

假设我想声明一个仅对函数f3和f4已知的变量。我将在何处以及如何声明此变量?

4 个答案:

答案 0 :(得分:1)

你能做这样的事吗?

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
          }
      }; 
   })();
}

答案 1 :(得分:1)

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

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则不会。

答案 2 :(得分:0)

只需在函数范围内声明变量,它就只对该函数可见。实施例

function f3() {
  var nestedVar = 3;
}

var notNested = nestedVar;   // this will not work

答案 3 :(得分:0)

也许是这样的:

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

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