I can't invoke a setter or getter in JavaScript

Question:

I was doing some object oriented exercises and in the solution the teacher used set and get . I realized that even doing as the teacher does not work. I can solve without get and set , but I was wondering 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 exit:

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

Answer:

When you use the get or set in JavaScript, it uses the language's default access format or definition.

So, to access, you must use:

obj.prop;

And to define:

obj.prop = "New Value";

See 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 accessors are not unique to classes. You can also use them on literal objects.

Scroll to Top