Max Koretskyi
Max Koretskyi

Reputation: 105507

How to prohibit modifying an object property with a getter

If I don't allow writing to an object property is it enough to define only a getter like this:

Object.defineProperty(fileNavigator, "isRoot", {
    get: function () {
        return this.currentPath.length === 0;
    }.bind(this)
});

var r = fileNavigator.isRoot;

// works OK

fileNavigator.isRoot = 4;

// throws

TypeError: Cannot set property isRoot of #<Object> which has only a getter

Which is expected. I'm wondering whether this is how it should be done?

Upvotes: 0

Views: 76

Answers (1)

jrsala
jrsala

Reputation: 1967

If you want the property to be recomputed each time you get it, which is your case, then yes, what you did is just fine, except for the .bind(this) which is unnecessary and wrong (thank you @torazaburo). If you absolutely want to bind the function, you need to use .bind(fileNavigator), or else the value of this is almost certainly not going to be fileNavigator, as intended.

If you want the property to be a readable constant, you don't need the getter function since it would not have to compute anything. Instead you use the other kind of property descriptor:

Object.defineProperty(obj, 'propertyName', {
    value: 'myValue',
    writable: false,
    enumerable: true,
    configurable: false
});

Upvotes: 2

Related Questions