I am trying to have a private property inside my class. I have a class called Person
and an instance of that class: person
declared with let person = new Person('name1')
.
I would like to save the name in person
's properties. I could simply do:
class Person {
constructor(name) {
this.name = name;
}
}
But I also want to perform some actions when changing this value, so I use a Setter:
class Person {
set name() {
// some actions
}
constructor(name) { }
}
But then how do I save the name? I would have to have another property for example _name
that would be used to save the actual value
class Person {
set name(newName) {
// some actions
return this._name;
}
set name(newName) {
this._name = name;
// some actions
}
constructor(name) {
this._name = name;
}
}
The problem is that _name
can be accessed outside with person._name
.
Is there a way to make it not accessible from outside?
I took inspiration from this answer (which doesn't use a getter and setter) and tried to enclose _name
when defining the getter and setter. The following code doesn't work:
class Person {
constructor(name) {
var _name = name;
Object.defineProperties(this, {
"name": {
"get": () => { return _name; },
"set": () => { _name = name; }
}
});
}
}