From 63dca59f272e178f6b0a26d58cd97a8c534179b1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ju=CC=88rg=20Lehni?= Date: Tue, 24 Nov 2026 22:22:49 +0100 Subject: [PATCH] fix(engine): let class field initializers set the class's static private fields - initialize_instance_elements copies the constructor's private methods and fields instead of keeping it borrowed while their initializers run --- core/engine/src/object/operations.rs | 18 +++++++++++++----- core/engine/src/tests/class.rs | 15 +++++++++++++++ 2 files changed, 28 insertions(+), 5 deletions(-) diff --git a/core/engine/src/object/operations.rs b/core/engine/src/object/operations.rs index 1c26f22c1f1..9093b6dc22a 100644 --- a/core/engine/src/object/operations.rs +++ b/core/engine/src/object/operations.rs @@ -1273,20 +1273,28 @@ impl JsObject { constructor: &Self, context: &mut Context, ) -> JsResult<()> { - let constructor_function = constructor - .downcast_ref::() - .js_expect("class constructor must be function object")?; + // Copied, as the initializers may change the constructor itself, e.g. its static private + // fields, which they couldn't while it's borrowed: + let (methods, fields) = { + let constructor_function = constructor + .downcast_ref::() + .js_expect("class constructor must be function object")?; + ( + constructor_function.get_private_methods().to_vec(), + constructor_function.get_fields().to_vec(), + ) + }; // 1. Let methods be the value of constructor.[[PrivateMethods]]. // 2. For each PrivateElement method of methods, do - for (name, method) in constructor_function.get_private_methods() { + for (name, method) in &methods { // a. Perform ? PrivateMethodOrAccessorAdd(O, method). self.private_method_or_accessor_add(name, method, context)?; } // 3. Let fields be the value of constructor.[[Fields]]. // 4. For each element fieldRecord of fields, do - for field_record in constructor_function.get_fields() { + for field_record in &fields { // a. Perform ? DefineField(O, fieldRecord). self.define_field(field_record, context)?; } diff --git a/core/engine/src/tests/class.rs b/core/engine/src/tests/class.rs index 98e3845f86f..2118dedd7ad 100644 --- a/core/engine/src/tests/class.rs +++ b/core/engine/src/tests/class.rs @@ -201,3 +201,18 @@ fn class_boolean_literal_getter_setter_names() { TestAction::assert_eq("c.false", 84), ]); } + +#[test] +fn class_field_initializer_sets_a_static_private_field() { + run_test_actions([ + TestAction::run(indoc! {r#" + class C { + static #count = 0; + id = ++C.#count; + } + new C(); + let c = new C(); + "#}), + TestAction::assert_eq("c.id", 2), + ]); +}