Defining read-only properties in JavaScript

You could instead use the writable property of the property descriptor, which prevents the need for a get accessor:

var obj = {};
Object.defineProperty(obj, "prop", {
    value: "test",
    writable: false
});

As mentioned in the comments, the writable option defaults to false so you can omit it in this case:

Object.defineProperty(obj, "prop", {
    value: "test"
});

This is ECMAScript 5 so won’t work in older browsers.

Leave a Comment