asutherland
asutherland

Reputation: 2969

Javascript: Is there a way to make a object property read only

I'd like to be able to do something like

foo.x = 7;

And then do something to make that property read only so that no other code can change it. IE i'd like

foo.x = 10; //should do nothing

To do nothing is there anyway to do that in JS?

Upvotes: 2

Views: 5423

Answers (4)

Tengiz
Tengiz

Reputation: 8449

Well, for backwards compatibility with old browsers you may need to define accessor functions. Alternatively you can use ready-made functionality provided by various frameworks (e.g. bob.js):

var obj = { };
//declare read-only property.
bob.prop.namedProp(obj, 'name', 'Bob', true);
//declare read-write property.
bob.prop.namedProp(obj, 'age', 1);

//get values of properties.
console.log(bob.string.formatString('{0} is {1} years old.', obj.get_name(), obj.get_age()));
//set value of read-write property.
obj.set_age(2);
console.log(bob.string.formatString('Now {0} is {1} years old.', obj.get_name(), obj.get_age()));

//cannot set read-only property of obj. Next line would throw an error.
// obj.set_name('Rob');

//Output:
//========
// Bob is 1 years old.
// Now Bob is 2 years old.

- Tengiz

Upvotes: 0

Moritz Roessler
Moritz Roessler

Reputation: 8651

You can use Object.defineProperty to do this.

Object.defineProperty(foo, "x", {writable:false})

See this Fiddle

If you want to make an whole Object unwritable, you could also use the Objects freeze method

Object.freeze(foo);

Upvotes: 0

Elias Van Ootegem
Elias Van Ootegem

Reputation: 76408

I think this is what you're looking for. Check the example under Writable attribute

It only works in browsers that offer ECMA5 support, though. For older browsers, you can't define a non-writeable propery, but you can set a private variable which can be used with a getter:

var foo = (function(x)
{
    var getX = function()
    {
        return x;
    };
    getX.valueOf = function()
    {
        return this();
    };
    return {x:x,getX:getX};
})(7);//pass constant value
foo.x === 7;//true
foo.x = 5;//will work
//BUT:
foo.getX();//returns 7, always
foo.getX;//returns 7, so can be used as though it weren't a method
//WARNING:
foo.getX = 213;//x is lost forever...

Upvotes: 1

benqus
benqus

Reputation: 1149

With ECMAScript5 you can achieve that:

var foo = {};

Object.defineProperty(foo, 'x', {
    value: 7,
    writable: false,
    configurable: false,
    enumerable: true
});

You might want to check out MDN JavaScript for ECMAScript5 stuff.

Upvotes: 6

Related Questions