How to remove the setter from a JavaScript object?
Asked Answered
S

1

5

Consider the following code:

var x = 0;

var o = {};

function getter() {
    return x;
}

Object.defineProperty(o, "y", {
    get: getter,
    set: function (y) {
        x = y;

        Object.defineProperty(o, "y", {
            get: getter
        });
    },
    configurable: true
});

My objective is to remove the setter and make the property o.y non-configurable after the setter has been called once. However it doesn't work as expected:

> x       // 0
> o.y     // 0
> o.y = 1 // 1
> x       // 1
> o.y     // 1
> o.y = 2 // 2
> x       // 2
> o.y     // 2

So my code did not work as expected, and I can't think of any other solution. Hence this question.

Sievers answered 3/10, 2014 at 5:13 Comment(0)
N
10

Think of the redefine operation like this: each key in the new definition replaces the corresponding key in the old definition. Since you do not specify a set key when you redefine the property, it retains its old value.

You need to explicitly include it as undefined in order to get rid of it, and in fact you don't need to set the getter at all because you are not changing it:

Object.defineProperty(o, "y", {
    set: undefined
});

Then, in my tests:

o.y     // 0
o.y = 1
o.y     // 1
o.y = 2
o.y     // 1
Nieman answered 3/10, 2014 at 5:17 Comment(2)
I reckon this is the trick that makes all sort of inner React objects (e.g. nextProps) unmodifiable.Cahill
@MarcoFaustinelli Set the docs at developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… -- there's a "writable" propertyName

© 2022 - 2024 — McMap. All rights reserved.