Check if the value of an object of a certain class has been changed

Asked

Viewed 22 times

1

I want when one value is changed within one object of a certain class, another to change as well. Example:

class minhaClasse{
  constructor(valor1, valor2){
    this.valor1 = valor1
    this.valor2 = valor2
    this.valores = {
      valor1: this.valor1,
      valor2: this.valor2
    }
  }
}

var meuObjeto = new minhaClasse(2,4)
console.log(meuObjeto.valor1, meuObjeto.valores)

meuObjeto.valor1++ // ou meuObjeto.valor1 = 3
//log esperado => 3 {"valor1": 3, "valor2": 4}
console.log(meuObjeto.valor1, meuObjeto.valores)

1 answer

1


You can use getters to do this. These values of this.valores can be a write protected (read-only) value pointer this.valor1 and this.valor2.

You can do it like this:

class minhaClasse {
  constructor(valor1, valor2) {
    this.valor1 = valor1
    this.valor2 = valor2
    const self = this;

    this.valores = {
      get valor1() {
        return self.valor1;
      },
      get valor2() {
        return self.valor2;
      }
    }
  }
}

var meuObjeto = new minhaClasse(2, 4)
console.log(meuObjeto.valor1, meuObjeto.valores)

meuObjeto.valor1++; // ou meuObjeto.valor1 = 3
// log esperado 3 {"valor1": 3, "valor2": 4}
console.log(meuObjeto.valor1, meuObjeto.valores)
meuObjeto.valores.valor1 = 200;
console.log(meuObjeto.valores); // dá  {"valor1": 3, "valor2": 4}

  • They just answered me on Stackoverflow gringo, they answered the same thing as you. Anyway, thank you very much!

  • 1

    @Luíshnrique both at the same time!. For, getters is the simplest way and as I wrote in the answer these values cannot be changed if configured in the correct way.

  • I had tried to use get valor1(){ return this.valor1 }, had not thought to create a pro variable this

Browser other questions tagged

You are not signed in. Login or sign up in order to post.