Here is the link to the topic:
There are a few questions I would like to ask
when are getters and setters called?
If i am not wrong setter is called when we would want to set the value in the object. similarly getter will run when we would want to print the value we want.
can we name getter and setter anything? if so then why error “getter and setter should be defined” displayed when i set the name to temp?
is it because a variable temp is already defined below, i.e.
let temp = thermos.temperature; // 24.44 in Celsius
why cant we do the calculations in getter like this:
let x = (5 / 9) * (this.fahrenheit - 32);
return x
how do we know if the temperature entered by user is in C or F. what if the temperature is already in C but when get is called the formula runs again. similarly what if its already in F but when setter runs the formula runs again.
wont the temperature become wrong then?
let temp = thermos.temperature; // 24.44 in Celsius
temp = thermos.temperature; // 26 in Celsius
why is a new variable let temp
is used here.
if it is used to print value then we were to print using console.log command like:
console.log(thermos.temperature)
would work fine??
class Book {
constructor(author) {
this._author = author;
}
// getter
get writer() {
return this._author;
}
// setter
set writer(updatedAuthor) {
this._author = updatedAuthor;
}
}
const novel = new Book('anonymous');
console.log(novel.writer); // anonymous
novel.writer = 'newAuthor';
console.log(novel.writer);
here we can see
console.log(novel.writer);
is used to print author name. but the object does not have a property named writer.
similrarly with this
novel.writer = 'newAuthor';
please correct me on things that i mentioned if i was wrong.
Thanks