Problem with Javascript Class Method

Asked

Viewed 44 times

0

I created a Javascript class and used var to leave the attributes encapsulated, but when I use the method setNome() it doesn’t work.

class AA {
  constructor(nome, idade) {
    var nome = nome;
    var idade = idade || "";

    this.getNome = () => { return nome; };
    this.setNome = (nome) => { nome = nome; };
  }
}

1 answer

5


If you are using classes, you have no reason to do this kind of thing. Create methods and properties using this, that will be encapsulated in class instances. Something like this:

class User {
  constructor(name) {
    this.name = name;
  }
  
  getName() {
    return this.name;
  }
  
  setName(newName) {
    this.name = newName;
  }
}

const u = new User('Unnamed');
console.log(u.getName());

u.setName('Luiz');
console.log(u.getName());

If you don’t want classes, you can use a type of Factory Function:

function createUser() {
  let name = 'Unnamed';
  
  const setName = (newName) => name = newName;
  const getName = () => name;
  
  return {
    setName,
    getName
  };
}

const u = createUser();

u.setName('Luiz');
console.log(u.getName());

Personally, I prefer this second approach most of the time, since I find it clearer. Also, there are not all those confusions brought by this javascript.

Browser other questions tagged

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