Search code examples
javascriptobjectjavascript-objects

How can methods in an object's prototype access property values of said object?


I created this function that is supposed to create/return an object with a custom prototype and basic properties. The issue is that when I try to call the methods from the object's prototype, I get the error: is not a function. My guess is that maybe it has to do with the this keyword, but I'm not sure. Why is this happening and how can I fix it?

const bookProto = {
  getPrice() {
    return this.price;
  },
  getInfo() {
    return `${this.title} by ${this.author}`;
  },
  addRating(str) {
    this.rating = str;
  },
  getRating() {
    return this.rating.length;
  },
};

function createBook(id, title, author, price) {
  let book = Object.create(bookProto);
  book = {
    id,
    title,
    author,
    price,
    rating: [],
  };
  return book;
}


Solution

  • Assigning a new object to book replaces the existing value. It doesn't merge with the object you have there.

    You need to assign the new property values one by one.

    function createBook(id, title, author, price) {
      const book = Object.create(bookProto);
      book.id = id;
      book.title = title;
      book.author = author;
      book.price = price;
      return book;
    }