Question about method get in javascript

6

A question, that it helps me to outsource a property, I have created a total property with the method get, but for what is necessary? Since doing a method I can call it the same with () and return what I want, instead of getting total () I do total () and already, I do not see much the novelty of the method get

class Factura {
  constructor(divisa, nombre, importe, IVA = importe * .1) {
    this._divisa = divisa;
    this._nombre = nombre;
    this._importe = importe;
    this._IVA = IVA;
  }

  presentacion (){
    return ' La factura ' + this._nombre + ' tiene un importe de ' + this._importe + ' ' + this._divisa + ' y con el IVA, se queda en '
  }
  get total(){
    return this._importe + this._IVA;
  }
  // totalDescuento(){
  //   return this._importe + this._IVA -
  // }
}

let factura1 = new Factura('eur', 'Transportes Chemita', 300);
let factura2 = new Factura('eur', 'Transportes Fran', 600);
let factura3 = new Factura('eur', 'Transportes Ailyn', 900);
let factura4 = new Factura('eur', 'Transportes alvaro', 9000);
let factura5 = new Factura('eur', 'Transportes carlos', 9200);
let factura6 = new Factura('eur', 'Transportes pepito', 9100);

document.write(factura1.presentacion() + factura1.total + ' eur' + '<br>');
document.write(factura2.presentacion() + factura2.total + ' eur' + '<br>');
document.write(factura3.presentacion() + factura3.total + ' eur' + '<br>');
document.write(factura4.presentacion() + factura4.total + ' eur' + '<br>');
document.write(factura5.presentacion() + factura5.total + ' eur' + '<br>');
document.write(factura6.presentacion() + factura6.total + ' eur' + '<br>');
    
asked by francisco dwq 15.01.2018 в 13:41
source

2 answers

1

Basically what the methods get and set provide you is to be able to establish logic when establishing and retrieving values of a property while maintaining the properties syntax of the object:

// Para recuperar valor
var valor = instancia.nombrePropiedad;
// Para establecer valor
instancia.nombrePropiedad = valor;

Imagine that you have a type Persona with a property nombreCompleto that returns the full name of the person (name + surnames) and also allows to establish this value:

class Persona {
  constructor(nombre, apellidos) {
    this.nombre = nombre;
    this.apellidos = apellidos;
  }

  get nombreCompleto(){
    return (this.nombre ? this.nombre + ' ' : '')
      + (this.apellidos ? this.apellidos : '');
  }
  
  set nombreCompleto(value){
    if (typeof value === 'string'){
      var parts = value.split(' ');
      this.nombre = parts[0];
      this.apellidos = parts.slice(1).join(' ');
    }
  }
  
}

var foo = new Persona('Asier', 'Villanueva Rodilla');
console.log(foo, foo.nombreCompleto);
foo.nombreCompleto='Pedro Picapiedra';
console.log(foo, foo.nombreCompleto);

As you see both to retrieve and to set the value, the syntax foo.nombreCompleto is used.

Up to ECMAScript 5 you would have to create two methods to do this: one to retrieve the value and another to establish it.

function Persona(nombre, apellidos) {
    this.nombre = nombre;
    this.apellidos = apellidos;
    this.getNombreCompleto = function(){
      return (this.nombre ? this.nombre + ' ' : '')
      + (this.apellidos ? this.apellidos : '');
    }
    this.setNombreCompleto = function(value){
      if (typeof value === 'string'){
        var parts = value.split(' ');
        this.nombre = parts[0];
        this.apellidos = parts.slice(1).join(' ');
      }
    }
}

var foo = new Persona('Asier', 'Villanueva Rodilla');
console.log({nombre: foo.nombre, apellidos: foo.apellidos}, foo.getNombreCompleto());
foo.setNombreCompleto('Pedro Picapiedra');
console.log({nombre: foo.nombre, apellidos: foo.apellidos}, foo.getNombreCompleto());

Here you would use the getNombreCompleto method to retrieve the value and the setNombreCompleto method to set it.

This way you abstract the internal implementation details of the developer that makes use of the external api of the object.

Perhaps the most practical case is when you want to add a validation to an existing property. With the previous method you would have to leave the variable that stores the value as private and create a method to set the value that the validation performs (like the setNombreCompleto ). This would force to modify all the lines of code that established the value of this property. Using a set method, you could add that internal validation without changing all the code that makes use of the external API.

    
answered by 15.01.2018 в 14:14
1

The getter / setters are very used mainly by frameworks and libraries because they make the pattern easier Binding or observable where the setters allow you to intervene when assigning the value to the property to perform another operation in addition to the assignment:

var persona ={
 nombre: null,
 apellido: null,
 get nombreCompleto(){
   return this.nombre + " " + this.apellido;
 },
 set nombreCompleto(value){
   var data = value.split(' ');
   this.nombre = data[0];
   this.apellido  = data[1];
   alert("se cambio el nombrea a " + this.nombreCompleto);
 }
};


persona.nombreCompleto = "Stack Overflow";

Note how it is possible to receive the name change notification with a clean and common syntax for all: persona.nombreCompleto = 'valor' . And it can be taken even further. For example, when assigning a value to the property nombreCompleto that a input related to the property is also edited:

  var persona ={
     nombre: null,
     apellido: null,
     get nombreCompleto(){
       return this.nombre + " " + this.apellido;
     },
     set nombreCompleto(value){
       var data = value.split(' ');
       this.nombre = data[0];
       this.apellido  = data[1];

       // editamos el valor del input nombre-completo
       document.getElementById("nombre-completo").value = this.nombreCompleto;
     }
    };


    persona.nombreCompleto = "Stack Overflow";
    setTimeout(function(){ 
      persona.nombreCompleto = "Einer Stack"
    }, 1000);
Nombre: <input type="text" id="nombre-completo" />

As for the setters, this would serve to process / format or clean the data before returning it to the client code. In C # the get / set are widely used by WPF for the facility they provide when defining properties.

But as has always been said, you have to find the right case to implement the set / get, otherwise, better to use standard functions / properties.

    
answered by 15.01.2018 в 14:14