Skip to content

[Bug]: Class Private Fields/Accessors/Methods must not be re-initialized on instance #13299

@jridgewell

Description

@jridgewell

💻

  • Would you like to work on a fix?

How are you using Babel?

Programmatic API (babel.transform, babel.parse)

Input code

(See "Prevent private class members from being added more than once" section in https://github.com/evanw/esbuild/releases/tag/v0.11.20#:~:text=Prevent%20private%20class%20members%20from%20being%20added%20more%20than%20once)

class Base {
  constructor(obj) {
    return obj;
  }
}

let counter = 0;
class Derived extends Base {
  #foo = ++counter;
  static get(obj) {
    return obj.#foo;
  }
}

const foo = {};
new Derived(foo);
assert.equals(Derived.get(foo), 1);

// This should throw an error, private fields must not be re-initialized
// on an object that already contains the field.
assert.throws(() => {
  new Derived(foo);
});
// ^ That should have thrown, but it doesn't.

// Must not re-initialize the field
assert.equals(Derived.get(foo), 1);
// But the counter is incremented (the initializer runs, but the field
// should not re-add)
assert.equals(counter, 2);

REPL

Configuration file name

babel.config.json

Configuration

{
  "presets": [
    [
      "@babel/preset-env",
      {
        "shippedProposals": true,
        "targets": {
          "chrome": "75"
        }
      }
    ]
  ]
}

Current and expected behavior

Currently, this will re-initialize the field #foo, but this is incorrect. It should throw an error when trying to initialize the field a second time.

Environment

  • Babel version: v7.14.1

Possible solution

We should create new initializePrivateFieldSpec, initializePrivateAccessorSpec, and initializePrivateMethodSpec (and static versions) helpers to initialize the field to a descriptor. Inside the helpers, we should check if the WeakMap/WeakSet that represents the transformed field already contains the instance key. If so, throw. Else, initialize.

Or, we could just have a simple checkPrivateFieldInitSpec which does the check, but doesn't initialize. We'd then call the check before initializing a field.

After creating the helpers, we should call them in the appropriate place in https://github.com/babel/babel/blob/main/packages/babel-helper-create-class-features-plugin/src/fields.js (look for any function that ends in "InitSpec").

Additional context

This is a medium difficulty issue, so could be tackled by someone with a little experience making changes to Babel.

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions