octopod
octopod

Reputation: 874

For immutability, what is the difference between using Object.defineProperty and Object.freeze?

MDN documents Object.freeze() as the solution for making a class immutable by preventing any changes to a class after initialization, like so:

class ExampleA {
    constructor(x) {
        this.x = x;
        Object.freeze(this);
    }
}

However, I have seen other people achieve the same effect by using Object.defineProperty() like so:

class ExampleB {
    constructor(x) {
        Object.defineProperty(this, "x", {value: x});
    }
}

At first glance, it seems like both ways achieve the same thing, that is being that I want this.x to be immutable. On top of that, using Object.defineProperty() lets me choose which properties to make immutable instead of making everything immutable like Object.freeze() does.

So I need to ask: In terms of achieving immutability, what is the preferred method? Are there any side effects that I might have missed by using Object.defineProperty() over Object.freeze()?

Upvotes: 2

Views: 650

Answers (1)

user6445533
user6445533

Reputation:

Both are totally different tools. Object.freeze works shallowly at the Object level, whereas Object.defineProperty works at the property level. Both can control the mutability of object types, but the latter can do a lot more. Shallowly means, that if a property contains another object type, this object is neither affected by Object.freeze nor by Object.defineProperty, but remains mutable.

Since you can achieve immutability with both tools only shallowly and deep immutability is expensive, I'd recommend to consider immutability as a policy rather than explicitly enforcing it.

Upvotes: 3

Related Questions