When the class has only one getter and no setter, it will report an error, but if I change the name of the getter, the error will disappear.
- The code that will report an error:
class Book {
constructor(author) {
this.author = author;
}
// getter
get author() {
return this.author;
}
}
const novel = new Book('anonymous');
console.log(novel.author);
//TypeError: Cannot set property author of #<Book> which has only a getter
- Code that will not report an error:
class Book {
constructor(author) {
this.author = author;
}
// getter
get writer() { //just change the name
return this.author;
}
}
const novel = new Book('anonymous');
console.log(novel.writer);
//anonymous
update:
- Why doesn’t this code report an error saying that there is only a getter and no setter?
class Book {
constructor(name) {
this._author = name;
}
// getter
get author() {
return this._author;
}
}
let a = new Book("Mike")
console.log(a.author)
2
Answers
That’s because you can’t have both a property and a getter with the same name
In the first example
this.author
is a getter and you are trying to overwrite it withthis.author = author
In the second example
this.author
is an unexisting propertyTwo issues here.
First, in your first example you’re assuming that a getter will implicitly create a field/property. It will not! Thus correct way to use it is:
Do note that in above code, I have created a property called
_author
and a getter calledauthor
. Thus when you call the getterauthor
it will return the underlying property_author
.Secondly, your second example works, since without you realizing there are actually two properties involved:
this.author
andthis.writer
Do note that JS is a dynamic language, and it will not complain of non-existent property.
Hope this helps, for more details read about getter and setters in JS here or on other sites!