Skip to content
This repository was archived by the owner on Jan 25, 2022. It is now read-only.
This repository was archived by the owner on Jan 25, 2022. It is now read-only.

Public fields "Define" semantics and subclasses #176

@rbuckton

Description

@rbuckton

I believe we may need to revisit the Set vs. Define debate of public fields in light of this scenario:

class Base {
  x = 1;
}
class Sub extends Base {
  set x(value) { console.log(value); }
}

// (a)
const obj = new Sub(); 

// (b)
obj.x = 2;

Without an in-depth understanding of the spec, a naïve developer might assume that (a) would print 1 and (b) would print 2, however this is not the case. According to the proposal, x will be Defined on the instance of obj during construction. This means that the field x on Base will override the accessor x on Sub, which seems to violate developer intuition that members on Sub should override members on Base. In fact, the only way for Sub to override x with an accessor would be to use Object.defineProperty in the constructor of Sub to replace the field with an accessor on the instance.

I only see two solutions to solve this issue:

  1. Split a field into two operations:
    1. Use Define on the prototype for Base to add a property with the descriptor: { enumerable: true, configurable: true, writable: true, value: undefined }
    2. Use Set in the constructor of Base to evaluate the initializer.
  2. Use Set semantics for fields.

Option 1 is the most consistent with the current semantics that use Define (a field on a subclass overrides a member on the superclass), but solves the above issue.

Option 2 is consistent with the state of existing compile-to-javascript languages over the last 6 years.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions