How to limit the values of a property of an object in JS?

0

When creating an object, the specialty field can only have the values 1, 2 or 3, how can I limit it?

function Sandskill(nom, edad, especialidad, comp){
    this.nombre = nom;
    this.edad = edad;
    this.especialidad = especialidad;
    this.comp = comp;

    this.nombreCompleto = function(){
        return this.nombre +" "+this.apellido;
    }
}

var s1 = new Sandskill ("e", "e", "1", "e");
    
asked by Eduardo 14.11.2017 в 16:19
source

3 answers

2

You have to do two things: on the one hand, add the check in the constructor, and on the other, avoid that you can modify the parameter later with invalid values. I have rewritten your object definition using the class syntax, for simplicity:

class Sandskill{
  constructor(nom, edad, especialidad, comp){
    this.nombre = nom;
    this.edad = edad;
    if(especialidad == 1 || especialidad == 2 || especialidad == 3){
      this._especialidad = especialidad;
    }else{
      throw new Error('Especialidad no válida');
    }
    this.comp = comp;

    this.nombreCompleto = function(){
        return this.nombre +" "+this.apellido;
    }
  }
  
  set especialidad(valor) {
     if(valor == 1 || valor == 2 || valor == 3){
       this._especialidad = valor;
     }
  }
  get especialidad() {
    return this._especialidad;
  }
}

var s1 = new Sandskill ("e", "e", "2", "e");
s1.especialidad=4; //será ignorado
console.log(s1.especialidad);
    
answered by 14.11.2017 / 17:26
source
1

I think that with a condition which validates the value of especialidad is enough, something like this:

function Sandskill(nom, edad, especialidad, comp){
    this.nombre = nom;
    this.edad = edad;
    if(especialidad == 1 || especialidad == 2 || especialidad == 3){
      this.especialidad = especialidad;
    }else{
      this.especialidad = null;
    }
    this.comp = comp;

    this.nombreCompleto = function(){
        return this.nombre +" "+this.apellido;
    }
}

var s1 = new Sandskill ("e", "e", "1", "e");
    
answered by 14.11.2017 в 16:23
1

Clean:

function Sandskill(nom, edad, especialidad, comp){
    this.nombre = nom;
    this.edad = edad;
    this.especialidad = especialidad > 0 && especialidad < 4 ?
                        'válida y es la número ${especialidad}' :
                        "inválida";
    this.comp = comp;
    this.show = () => this.especialidad;
}

 var s1 = new Sandskill ("e", "e", "1", "e");
 console.log('La especialidad es ${s1.show()}');
    
answered by 14.11.2017 в 17:51