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.

A private setter in JavaScript is an accessor method defined within a class using the set keyword combined with a # prefix. It intercepts assignment operations to a specific private identifier, executing custom logic while strictly restricting invocation to the internal lexical scope of the class. Attempting to invoke a private setter from outside its enclosing class results in a SyntaxError.

Syntax

class ClassName {
  set #identifier(parameter) {
    // Assignment logic
  }
}

Mechanics and Rules

  1. Lexical Scoping: The # prefix denotes a private name. The JavaScript engine enforces this encapsulation at parse time. The setter can only be triggered via this.#identifier = value from within the class body.
  2. Parameter Requirement: Like public setters, a private setter must be defined with exactly one parameter.
  3. Namespace Collision: A private setter can share an identifier with a private getter (get #identifier()), creating a complete private accessor pair. However, it cannot share an identifier with a private data field. Declaring #prop; and set #prop(val) in the same class throws a SyntaxError.
  4. Inheritance: Private setters are not inherited. Subclasses cannot access or override the private setters of their parent classes.

Code Example

class TypeProcessor {
  // Private data field
  #internalState;

  // Private setter declaration
  set #normalizedState(value) {
    this.#internalState = typeof value === 'string' ? value.trim() : String(value);
  }

  // Public method interacting with the private setter
  process(rawInput) {
    // Triggers the private setter internally
    this.#normalizedState = rawInput; 
  }

  getState() {
    return this.#internalState;
  }
}

const processor = new TypeProcessor();
processor.process("   data   "); 

console.log(processor.getState()); // "data"

// The following throws a SyntaxError: 
// Private field '#normalizedState' must be declared in an enclosing class
// processor.#normalizedState = "new data"; 

Static Private Setters

Private setters can also be applied to the class constructor itself rather than its instances by using the static keyword. Static private setters are invoked on the class object (ClassName.#identifier = value) rather than this (unless this refers to the class within a static context).
class Configuration {
  static #configValue;

  static set #init(value) {
    Configuration.#configValue = value;
  }

  static setup(val) {
    this.#init = val; // 'this' refers to the Configuration class
  }
}
Master JavaScript with Deep Grasping Methodology!Learn More