I cannot invoke a Setter or getter in Javascript

Asked

Viewed 88 times

3

I was doing some object orientation exercises and in the solution the teacher used set and get. I realized that even if I do it like the teacher, it doesn’t work. I can solve it without get and set, but wanted to know how to use them in Javascript.

class Endereco{
  constructor(rua) {
    this.rua = rua;
  }

  set novaRua(nova){
    this.rua = nova;
  }

let E1 = new Endereco(null);
E1.novaRua("rua x");
console.log(E1.rua);

The way out:

Uncaught TypeError: E1.novaRua is not a function
  at aula8.js:77

2 answers

5


When you use the advisors get or set in Javascript, it uses the default access format or definition of the language.

So, to access, you must use:

obj.prop;

And to define:

obj.prop = "New Value";

Take an example:

class Person {
  name = undefined;
  
  set name(name) {
    this.name = name;
  }
  
  get name() {
    return this.name;
  }
}

const p = new Person();
console.log(p.name); // undefined
p.name = 'Luiz';
console.log(p.name); // Luiz

Note that these advisors are not class exclusive. You can also use them in literal objects.

4

There’s a key missing { to complete the class declaration syntax and there was a mistake in its interpretation of the Setter.

Setter binds an object property to a function to be called when there is an attempt to define that property.
In Javascript, a Setter can be used to execute a function whenever a specified property is changed. Setters are most often used in conjunction with getters to create a type of pseudo-property.

class Endereco {
  constructor(rua) {
    this.rua = rua;
  }

  set novaRua(nova) {
    this.rua = nova;
  }
} //<-- Estava faltando essa chave

let E1 = new Endereco(null);
E1.novaRua = "rua x"; //<-- Apenas defina o valor da propriedade.
console.log(E1.rua);

  • I think the only thing missing was the lock when he was transcribing the code for the question, otherwise the error he was going to receive would be Uncaught SyntaxError: Unexpected identifier, since he couldn’t even try to invoke (incorrectly) the Setter, since the parser would have failed earlier. :-)

  • 1

    @Luizfelipe, probably yes, but I already solved a problem that was generated in the transcription of the question.

Browser other questions tagged

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