Doubt about getter in Javascript

2

I've been studying computed properties of Vues.js that these computed properties use getters and setters too, and studying on get I fell into this sample code on the mozilla :

var expr = "foo";

var obj = {
   get [expr]() { 
      return "bar";
   }
};

console.log(obj.foo);      // bar
  

That's when the question came to me:

  • Get is only used to work with the value of the variable while keeping the original value of the same or would you have any other application?
asked by anonymous 30.10.2018 / 19:02

1 answer

5
  

Is it only used to work with the value of the variable while maintaining the original value of the variable or would it have any more applications?

No, a getter can return something only based on the state of variables or properties (private or not), not just the value of one of them. It's very much in the line of Vue's computed properties that you've cited, it has several utilities. Because getters are functions, they can basically return anything.

For example, a getter that makes an account and returns the result:

var divisao = {
   dividendo: 10,
   divisor:   5,
   get resultado() { 
      return this.dividendo/this.divisor;
   }
};
console.log(divisao.resultado); // 2
divisao.dividendo = 50;
console.log(divisao.resultado); // 10
    
30.10.2018 / 19:11