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

qodeninja picture qodeninja · Mar 11, 2010 · Viewed 54.4k times · Source

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?

Answer

Christian C. Salvadó picture Christian C. Salvadó · Mar 11, 2010

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

UPDATE: Nowadays, the ECMAScript 5 standard is widely supported. It 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 existing properties.

The Object.freeze method will completely lock an object. Objects will stay exactly as they were when you freeze them. Once an object is frozen, it cannot be unfrozen.

More info: