我正在使用显示模块模式,如下所示:
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。感谢您的建议。
最佳答案
使用Object.defineProperty
而不是仅返回对象文字:
var out = {};
if ( Object.defineProperty ) {
Object.defineProperty(out, 'GetTheVar', {
value: InnerGetTheVar,
writable: false
});
} else {
out.GetTheVar = InnerGetTheVar;
}
return out;
关于javascript - javascript闭包:保护内部变量,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/12135017/