Getters and setters in javascript [closed]

-1

I am entering the world of programming. It is hard for me to understand the getters and setters, I understand that they are for data validation, but the problem is that the object section comes from classes and from what I see only use the getters .

Exactly the getters are to obtain data of a function? Does not the function simply do that? Could you explain me with real life examples to understand better? I appreciate the help

    
asked by Joseamica 13.01.2018 в 06:19
source

2 answers

1

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.

    
answered by 13.01.2018 в 07:48
0

All functions create their own scope, so no one outside of this can access the variables declaradas in it. To combat this, comes the getter that allows us to visualize the properties and the setter that allows us to modify it.

The getter only returns the property and that's why we can get it.

The setter only receives one parameter and assigns it to the property.

function data() {
 this.safe = true; // propiedad
 var that = this; // Guardamos el contexto de data
 this.getter = () => that.safe;
 this.setter = newSafe => { that.safe = newSafe; };
}

    var b = new data(); // Instanciamos el constructor

    console.log(b.getter()); // Sirve para obtener
    b.setter("Cambiado"); // Sirve para cambiar
    console.log(b.getter()); // Volvemos obtener para ver el cambio
 
    
answered by 13.01.2018 в 14:30