The getters and setters are part of the public interface, which through public methods allow you to modify or obtain private data, for example in a class "Book" an attribute is editorial and by encapsulation is private (only accessible within it) class), the setEditorial method will allow you to access the private attribute and modify it, getEditorial will also access the attribute and return it.
For example:
function Libro(editorial){
const that = this;
this.editorial = editorial;
return {
setEditorial: function(editorial){
that.editorial = editorial;
},
getEditorial: function() {
return that.editorial;
}
};
}
const libro = Libro("ejemplo editorial");
console.log(libro.getEditorial());//mediante un método público se accede a un atributo privado
console.log(libro.editorial);//undefined porque no se puede acceder a un atributo privado desde afuera de la clase
libro.setEditorial("cambio de editorial");
console.log(libro.getEditorial());//imprime "cambio de editorial"
//Sólo para que veas qué contiene el objeto,
//verás que sólo son las funciones y no hay algún atributo editorial
console.log(libro);
If you execute that code you will see an exit:
ejemplo editorial
undefined
cambio de editorial
undefined
corresponds to this line: console.log(libro.editorial);
since the attribute is private.
Only the getters and setters can access the publisher because in the return
only public methods that do have access to the editorial attribute are returned thanks to that
.
Notes: I used a closure for this example but it is not recommended, since each function uses memory, but the objective was to show the public interface. p>
The reason of const that = this
is for the context in which public functions are executed that must refer to this
but of the function Book.
function Libro(editorial){
const that = this;
this.editorial = editorial;
return {
setEditorial: function(editorial){
that.editorial = editorial;
},
getEditorial: function() {
return that.editorial;
}
};
}
const libro = Libro("ejemplo editorial");
libro.editorial = "nueva editorial";
console.log(libro.editorial + " --- " + libro.getEditorial());
//Sólo para que veas qué contiene el objeto,
//verás que sólo son las funciones y un atributo editorial, diferente al definido en la función Libro
console.log(libro);
As you can see, first print libro.editorial
and then libro.getEditorial()
and ARE DIFFERENT, this is because when you put libro.editorial = "nueva editorial"
another attribute is created different from the one in the Book function.