October 24, 2023
TestsSource
- Are private properties really private?
Source Code
The source code we wrote during the event.
private-class-properties.spec.js
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');
});
});