js class private code example
Example 1: private methods in classesjs
class Something {
#property;
constructor(){
this.#property = "test";
}
#privateMethod() {
return 'hello world';
}
getPrivateMessage() {
return this.#privateMethod();
}
}
const instance = new Something();
console.log(instance.property);
console.log(instance.privateMethod);
console.log(instance.getPrivateMessage());
Example 2: javascript function as class new private
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();
Example 3: js class private
class ClassWithPrivateField {
#privateField;
constructor() {
this.#privateField = 42;
this.#randomField = 666; # Syntax error
}
}
const instance = new ClassWithPrivateField();
instance.#privateField === 42;