Skip to main content

Documentation Index

Fetch the complete documentation index at: https://docs.syntblaze.com/llms.txt

Use this file to discover all available pages before exploring further.

Public class fields are properties declared directly within a class body, allowing developers to attach state to class instances without explicitly defining them inside the constructor method. By default, fields declared this way are publicly accessible, writable, enumerable, and configurable on the instantiated object.
class InstanceState {
  // Uninitialized public field (implicitly undefined)
  uninitializedField;

  // Initialized public field
  initializedField = 'default value';

  // Public field assigned to an arrow function
  boundMethod = () => {
    return this.initializedField;
  };
}

Technical Mechanics

Instance Allocation Public fields are created as own properties on the instance itself via [[DefineOwnProperty]] semantics. They are not attached to the class prototype. This means every time a class is instantiated, a new copy of the field and its evaluated value is allocated in memory. Evaluation Timing The initialization of public fields is strictly ordered during the object construction phase:
  • Base Classes: Field initializers are evaluated and assigned immediately before the constructor body executes.
  • Derived Classes: Field initializers are evaluated and assigned immediately after the super() call returns. Attempting to access this before super() will result in a ReferenceError.
class Base {
  baseField = 10;
  
  constructor() {
    // baseField is already initialized here
    console.log(this.baseField); 
  }
}

class Derived extends Base {
  derivedField = 20;
  
  constructor() {
    // super() must be called before derivedField is initialized
    super(); 
    // derivedField is now initialized
    console.log(this.derivedField); 
  }
}
Lexical Scoping and this Binding The initializer expression of a public field is evaluated within the class scope. The this keyword inside the initializer refers to the instance currently being constructed. When a public field is assigned an arrow function, the arrow function lexically binds this to the instance, ensuring the context remains strictly tied to the object regardless of how the method is invoked.

Static Public Fields

By prepending the static keyword, a public field is attached directly to the class constructor object rather than to individual instances.
class Configuration {
  static defaultTimeout = 5000;
  static environment = 'production';
}

// Accessed via the class itself, not an instance
console.log(Configuration.defaultTimeout); // 5000
Static fields are evaluated only once, at the time the class definition is evaluated by the JavaScript engine. They are added as own properties of the class constructor function.
Master JavaScript with Deep Grasping Methodology!Learn More