Doubt about getter in Javascript

Asked

Viewed 46 times

3

I saw studying about computed properties of Vues.js that these computed properties use getters and setters also, and studying on the get I fell into this example code on the Mozilla:

var expr = "foo";

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

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

Then the doubt came to me:

  • Get is only used to work with the variable value while maintaining the original value of the variable or would have some other application?

1 answer

5


is only used to work with the variable value while maintaining the original value of the variable or would have more application?

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 is well in line with the Vue computed properties you quoted, it has several utilities. Since getters are functions, they can return basically anything.

For example, a getter who 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

  • Oops, thanks for the answer man. Wouldn’t you have an example to give us? Because what I found was just this example of the Mozilla site and left me with more doubts than certainties. :(

  • I put an example

  • Very good man, understood perfectly!

Browser other questions tagged

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