1class Something {
2 #property;
3
4 constructor(){
5 this.#property = "test";
6 }
7
8 #privateMethod() {
9 return 'hello world';
10 }
11
12 getPrivateMessage() {
13 return this.#privateMethod();
14 }
15}
16
17const instance = new Something();
18console.log(instance.property); //=> undefined
19console.log(instance.privateMethod); //=> undefined
20console.log(instance.getPrivateMessage()); //=> hello worl
1// Javascript Function that behaves as class, with private variables
2function Person(name){
3 const birth = new Date();
4 this.greet = () => `Hello my name is ${name}. I was born at ${birth.toISOString()}`;
5}
6
7const joe = new Person("Joe");
8joe.greet(); // Hello my name is Joe. I was born at 2021-04-09T21:12:33.098Z
9// The birth variable is "inaccessible" from outside so "private"
1class ClassWithPrivateField {
2 #privateField;
3
4 constructor() {
5 this.#privateField = 42;
6 this.#randomField = 666; # Syntax error
7 }
8}
9
10const instance = new ClassWithPrivateField();
11instance.#privateField === 42; // Syntax error
12