javascript闭包:保护内部变量

时间:2012-08-27 00:23:22

标签: javascript

我使用的揭示模块模式有点像这样:

var SomeClosure = function () {

  var SomeInnerVar = 4;

  function InnerGetTheVar() {
     return SomeInnerVar;
  } 

  function InitClosure() {
       // there's something else happening here that requires me to 
       // wait for document.ready before initializing the closure
       setInterval(IncreaseSomeInnerVar, 10000);
  }

  function IncreaseSomeInnerVar() {
     SomeInnerVar = SomeInnerVar  + 1;
  }

  InitClosure();

  return  {
     GetTheVar: InnerGetTheVar
  }
}

$(document).ready(function () {

   SomeClosure = SomeClosure();
}); 

现在为什么如果在控制台中我输入:

SomeClosure.GetTheVar = 2;
SomeClosure.GetTheVar; // outputs 2!

为什么闭包不会保持SomeInnerVar?我不希望外部范围能够像这样更改SomeInnerVar。

感谢您的建议。

2 个答案:

答案 0 :(得分:2)

实际上,SomeInnerVar在这个意义上仍然是“受保护的”。但是,您使用值SomeClosure覆盖GetTheVar的{​​{1}}属性,该值在同一意义上不受“保护”。换句话说,您不是在修改2,而是在修改SomeInnerVar

答案 1 :(得分:1)

使用Object.defineProperty

,而不只是返回对象文字
var out = {};

if ( Object.defineProperty ) {
    Object.defineProperty(out, 'GetTheVar', {
        value: InnerGetTheVar,
        writable: false
    });
} else {
    out.GetTheVar = InnerGetTheVar;
}

return out;