How can you make a variable/Object read only in Javascript? [duplicate]

我是研究僧i 提交于 2019-11-28 06:49:28
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.

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:

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 cannot be modified after object creation.

I'm trying to think of a practical use for this.

CMS

In the current widely available implementation, ECMAScript 3 there is no support for real immutability.

The ECMAScript 5 standard adds the Object.seal and Object.freeze methods.

The Object.seal method will prevent property additions, still allowing the user to write to or edit the properties.

The Object.freeze method will completely lock an object. Objects will stay exactly as they were when you freeze them and once an object has been frozen it cannot be unfrozen.

In conclusion, for real object immutability we will have to wait until ECMAScript 5.

More info:

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!