// 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 Person {
constructor(name) {
var _name = name
this.setName = function(name) { _name = name; }
this.getName = function() { return _name; }
}
}