I'm learning the basic syntax of classes in Javascript and an important question has arisen. Using the constructor I intend to create and set the property this.name
, while using the getters and setters I intend to get and modify this._name
assuming that _name is an 'internal' property of the object and therefore should not be modifiable without the use of the set. What I can't understand is the following:
"use strict";
class Admin {
constructor(name) {
this.name = name;
};
get name() {
return this._name;
};
set name(value) {
if (value.length < 4) {
console.log('Nombre demasiado corto!');
return;
};
this._name = value
};
};
let admin = new Admin('Julio');
//Por qué _name === name si todavía no he ejecutado el set?
//_name no debería existir, debería ser undefined
console.log(admin._name);
console.log(admin.name);
console.log(admin);
admin.name = 'Roberto';
//Por qué _name === name si el set no afecta a name, sino a _name?
//admin.name debería ser 'Julio' y admin.name 'Roberto'
console.log(admin._name);
console.log(admin.name);
console.log(admin);
//otra duda que tengo es porqué al mandar admin a consola, se muestra _name pero no name dentro del objeto
As you can see, my main doubt is regarding the set and the constructor, which add _name even though I have not executed the set.