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.
Use
this.nome
.– Augusto Vasques