tc39 / proposal-class-fields

Orthogonally-informed combination of public and private fields proposals
https://arai-a.github.io/ecma262-compare/?pr=1668
1.72k stars 113 forks source link

Proxy nested inside of the Prototype Chain #330

Open wentout opened 3 years ago

wentout commented 3 years ago

Hi!

Sorry, if this is something already discussed, give me a link please.

Let assume situation there is a nested Proxy in prototype chain.


class MyClass {
    someField = 'example';
    constructor () {
        this.otherField = 'other example'
    }
}

Reflect.setPrototypeOf(MyClass.prototype, new Proxy({}, {
    get (target, propName, receiver) {
        debugger;
    },
    set (target, propName, value, receiver) {
        debugger;
        return true;
    }
}));

const myInstance = new MyClass;
debugger;

So, we can review this example by copy and paste. Current status for this example for latest Chrome, Node.js and Firefox is the following:

And I wonder why it is made like this?

I assume this was not fully described, and as class fields are still in testing phase, the hidden mechanics of how they work indeed just skipped for Proxy traps. The other scenario is that someField is defined using Object.defineProperty or something like this. I can understand if we will keep this behavior. However TypeScript, for example, moves someField declaration to the constructor. And that means though keeping the same conditions for Proxies.

ljharb commented 3 years ago

Class fields are stage 4, as of today, and have been shipped in browsers for quite awhile - not in any "testing phase".

Private fields are like internal slots on builtins - they do not, by design, tunnel through Proxies. Public fields, however, should trigger proxy traps all the same, and in your example, the issue isn't about Proxy at all - it's that class fields use [[Define]] semantics, and thus, do not trigger setters on the prototype chain (also by design).

nicolo-ribaudo commented 3 years ago

However TypeScript, for example, moves someField declaration to the constructor.

If you want TypeScript to follow the spec (I think it will do it by default in the future), you can use the useDefineForClassFields option.