tc39 / proposal-structs

JavaScript Structs: Fixed Layout Objects
http://tc39.es/proposal-structs/
622 stars 11 forks source link

Can you stamp a private field on a struct? #42

Open bakkot opened 1 month ago

bakkot commented 1 month ago

Capturing a topic discussed in plenary and on Matrix.

The accursed return override trick lets you put private fields on (almost) any object, even a frozen object:

class ReturnOverride { constructor(o) { return o; } }

class Stamp extends ReturnOverride {
  #x = 1;
  static isStamped(o) {
    return #x in o;
  }
}

let object = Object.freeze({});
console.log(Stamp.isStamped(object)); // false
new Stamp(object);
console.log(Stamp.isStamped(object)); // true

Should you be allowed to do this to a struct? This violates the "fixed layout" goal, under common implementations of private fields.

If no, how exactly is it denied?

Is the failure when you try to instantiate a class with a private field and its super constructor returns a struct? That's one option; that's how it works for WindowProxy.

Another option is to say that classes are forbidden from extending structs: i.e., it is an error if super() returns a struct (either because of class extends Struct or because of a return override). As a consequence you mechanically would not be able add a private field to a struct. I like this option.

cc @erights