private class js code example

Example 1: javascript function as class new private

// Javascript Function that behaves as class, with private variables
function Person(name){
    const birth = new Date();
    this.greet = () => `Hello my name is ${name}. I was born at ${birth.toISOString()}`;
}

const joe = new Person("Joe");
joe.greet(); // Hello my name is Joe. I was born at 2021-04-09T21:12:33.098Z
// The birth variable is "inaccessible" from outside so "private"

Example 2: js class private

class ClassWithPrivateField {
  #privateField;
  
  constructor() {
    this.#privateField = 42;
    this.#randomField = 666; # Syntax error
  }
}

const instance = new ClassWithPrivateField();
instance.#privateField === 42; // Syntax error