// Javascript Function that behaves as class, with private variables
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(); // Hello my name is Joe. I was born at 2021-04-09T21:12:33.098Z
// The birth variable is "inaccessible" from outside so "private"
class ClassWithPrivateField {
#privateField;
constructor() {
this.#privateField = 42;
this.#randomField = 666; # Syntax error
}
}
const instance = new ClassWithPrivateField();
instance.#privateField === 42; // Syntax error
class MyClass
{
// Prepend hash to make it private. Browser support at:
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes/Private_class_fields#browser_compatibility
// Dynamic access (ie: this.#[fieldName]) is disallowed by design.
#myPrivateMethod() {
// do private things
}
}
class Person {
constructor(name) {
var _name = name
this.setName = function(name) { _name = name; }
this.getName = function() { return _name; }
}
}