Can you help please,
I don’t understand exactly what’s the role of “get” and “set” besides the diffrences between them .
Thanks for any help !
Hi @hamza9!
I will use the example that Mosh gave (video link below), as I found that to be very clear and helpful.
You have the following object:
person = {
firstName: "Bob",
lastName: "Ross"
}
Let’s say that you wanted to access this person’s full name, you could do this as follows:
console.log(person.firstName + " " + person.lastName)
OR
console.log(`${person.firstName} ${person.lastName}`)
This is a pain to access the first name this way, as that is a lot of typing, and would be a pain to access if you had to do it a lot. Instead, we could use a getter
person={
firstName: "Bob",
lastName: "Ross",
get fullName() {
return `${person.firstName} ${person.lastName}`
}
}
now, if you want to access this person’s full name, all you need to do is say:
console.log(person.fullName)
// Notice, how you don't need to add () after fullName.
//This is because you are using get.
Though, let’s say you wanted to change this person’s full name. Here we could use a setter:
person={
firstName: "Bob",
lastName: "Ross",
get fullName() {
return `${this.firstName} ${this.lastName}`
},
set fullName(name) {
const partsOfName = name.split(" ");
this.firstName = partsOfName[0];
this.lastName = partsOfName[1];
}
}
Now, to change the name of person, all you need to do is say:
person.fullName = "Charlie Sheen"
and because you are using a setter, it will run the function fullName(name) and input “Charlie Sheen” as the name.
This is a great youtube video explaining what getters and setters are, and why you might use them:
Let me know if you have any other questions
why the getters function use : {person.firstName} why not : {this.firstName} ?
Hi @aldhaneka,
You’re right, I just copied and pasted the earlier console.log() statement shown below.
console.log(`${person.firstName} ${person.lastName}`)
I think it would be better to use this instead.