Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 250
qodeninja Avatar asked Mar 11 '10 20:03

qodeninja


People also ask

How do you make a variable readOnly in JavaScript?

You can make a property read-only by using the Object. defineProperty(obj, prop, descriptor) static function.

What is read-only property in JavaScript?

The readOnly property sets or returns whether a text field is read-only, or not. A read-only field cannot be modified. However, a user can tab to it, highlight it, and copy the text from it. Tip: To prevent the user from interacting with the field, use the disabled property instead.

What is read-only error in JavaScript?

The JavaScript strict mode-only exception "is read-only" occurs when a global variable or object property that was assigned to is a read-only property.


2 Answers

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:

  • ECMAScript 5 Objects and Properties
like image 143
Christian C. Salvadó Avatar answered Oct 13 '22 19:10

Christian C. Salvadó


EDIT: This was writtent 10 years ago. I don't consider this to be an up to date answer.

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.

like image 31
spender Avatar answered Oct 13 '22 20:10

spender