JSlang.dev

JavaScript Deep Dives with Wolfram. Since 2015
Inclusive, Test-Driven, Spec-Focused, Collaborative.

October 24, 2023
TestsSource
Private Class Feature(s)

Source Code

The source code we wrote during the event.

import {strict as assert} from 'assert';

describe('Are private properties really private?', () => {
  it('creating a class with a private property can not be accessed from the instance (outside), it will throw', () => {
    class X {
      #privateProp = 42;
    }
    const x = new X();
    assert.throws(() => eval('x.#privateProp'), SyntaxError);
  });
  it('using the private property inside the class, does not throw', () => {
    class X {
      #privateProp = 42;
      get prop() {
        return this.#privateProp / 2;
      }
    }
    const x = new X();
    assert.equal(x.prop, 21);
  });
  it('accessing a static private prop can be done from inside the class', () => {
    class X {
      static #privateProp = 42;
      get prop() {
        return X.#privateProp;
      }
    }
    const x = new X();
    assert.equal(x.prop, 42);
  });
  it('using a static getter accessing a private property is possible', () => {
    class X {
      static #privateProp = 42;
      static get prop() {
        return X.#privateProp;
      }
    }
    assert.equal(X.prop, 42);
  });
  it('a private method is NOT visible on the classes` prototype', () => {
    class X {
      #privateMethod() {};
      publicMethod() {}
    }
    assert.equal(typeof X.prototype.publicMethod, 'function');
    assert.equal(typeof X.prototype['#privateMethod'], 'undefined');
  });
});