我使用的揭示模块模式有点像这样:
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。
感谢您的建议。
答案 0 :(得分:2)
实际上,SomeInnerVar
在这个意义上仍然是“受保护的”。但是,您使用值SomeClosure
覆盖GetTheVar
的{{1}}属性,该值在同一意义上不受“保护”。换句话说,您不是在修改2
,而是在修改SomeInnerVar
。
答案 1 :(得分:1)
var out = {};
if ( Object.defineProperty ) {
Object.defineProperty(out, 'GetTheVar', {
value: InnerGetTheVar,
writable: false
});
} else {
out.GetTheVar = InnerGetTheVar;
}
return out;