如何在 Javascript 中使变量/对象只读?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2428409/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can you make a variable/Object read only in Javascript?
提问by qodeninja
Possible Duplicate:
Can Read-Only Properties be Implemented in Pure JavaScript?
I have an Object that I only want to be defined when constructed. How can I prevent the Object reference from being changed?
我有一个对象,我只想在构造时定义它。如何防止对象引用被更改?
采纳答案by spender
Realistically... by not overwriting it. You could always control access by wrapping it in an object that only offers GetObj with no SetObj, but of course, the wrapper is equally liable to overwriting, as are its "private" member properties that would be "hidden" via the GetObj method.
实际上......通过不覆盖它。您总是可以通过将它包装在一个只提供 GetObj 而没有 SetObj 的对象中来控制访问,但是当然,包装器同样容易被覆盖,因为它的“私有”成员属性将通过 GetObj 方法“隐藏”。
Actually, question is a dupe:
实际上,问题是一个骗局:
Can Read-Only Properties be Implemented in Pure JavaScript?
EDIT:
编辑:
After reading http://javascript.crockford.com/private.html, it is possible to use closure to create variable references that are truely inaccessible from the outside world. For instance:
阅读http://javascript.crockford.com/private.html 后,可以使用闭包来创建外部世界真正无法访问的变量引用。例如:
function objectHider(obj)
{
this.getObject=function(){return obj;}
}
var someData={apples:5,oranges:4}
var hider=new objectHider(someData);
//... hider.getObject()
where the reference to obj in objectHider cannotbe modified after object creation.
在对象创建后无法修改objectHider 中对 obj 的引用。
I'm trying to think of a practical use for this.
我正在尝试为此考虑实际用途。
回答by CMS
In the current widely available implementation, ECMAScript 3there is no support for real immutability.
在当前广泛可用的实现中,ECMAScript 3不支持真正的不变性。
UPDATE:Nowadays, the ECMAScript 5standard is widely supported. It adds the Object.sealand Object.freezemethods.
更新:如今,ECMAScript 5标准得到广泛支持。它添加了Object.seal和Object.freeze方法。
The Object.sealmethod will prevent property additions, still allowing the user to write to or edit the existing properties.
该Object.seal方法将阻止属性添加,但仍允许用户写入或编辑现有属性。
The Object.freezemethod will completely lock an object. Objects will stay exactly as they were when you freezethem. Once an object is frozen, it cannot be unfrozen.
该Object.freeze方法将完全锁定一个对象。当您冻结对象时,它们将完全保持原样。一旦对象被冻结,就无法解冻。
More info:
更多信息:

