skip to Main Content

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.

  1. 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
  1. 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:

  1. 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


  1. 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 with this.author = author

    In the second example this.author is an unexisting property

    Login or Signup to reply.
  2. Two 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:

    class Book {
      constructor(author) {
        this._author = author;
      }
      // getter
      get author() {
        return this._author;
      }
    }
    

    Do note that in above code, I have created a property called _author and a getter called author. Thus when you call the getter author it will return the underlying property _author.

    Secondly, your second example works, since without you realizing there are actually two properties involved:

    this.author and this.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!

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search