top | item 33357071

(no title)

bluetech | 3 years ago

> Object.freeze does make an object immutable

If you look at the Hardened Javascript example:

    const makeCounter = () => {
      let count = 0;
      return harden({
        incr: () => (count += 1),
        decr: () => (count -= 1),
      });
    };
The "counter object" here is mutable. I think that's what they mean.

discuss

order

vanderZwan|3 years ago

Well yeah, it's closing over a variable that is not actually part of the properties of the function objects that are returned.

Object.freeze makes the shape (and therefore the properties) of an object immutable. It makes no guarantees about variables being closed over by a function. Those are different semantics altogether.

That feels similar to my earlier example of properties of nested objects not being affected by Object.freeze. And in this case, being able to freeze closed variables would in a sense mean exposing those variables. Which is not how closed variables work in JS (in fact it's one of the best ways to mimic "private properties" - except they're not really properties).

It's a good example of a potential gotcha though!

afiori|3 years ago

There are two types of immutability in JS: one is rebinding a variable (forbidden by the const keyword) and the other is modifying an object (forbidden by freeze)

In javascript these are similar as environment closures behave sort of similar to prototype chains.

cromwellian|3 years ago

One way to work around this is to serialize the argument to harden back to source, eval() it and then harden, which will prevent the captures from working.