private variables class js code example

Example 1: js class private

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

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

Example 2: 3. What are private member variables. in js

function ConstructorCar(initValue) {   this.publicMember = initValue;   let _privateMember = initValue; //private member   this.getPrivateMember = function() { return _privateMember; }   this.setPrivateMember = function(v) { _privateMember = v; }}ConstructorCar.prototype.drive = function() {  //this._privateMember undefined  console.log(“Drive! “+this._privateMember); }const car2 = new ConstructorCar(100);console.log(“getPrivateMember: “+car2.getPrivateMember());car2.drive();