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

Time:10-12

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? Thanks in advance!

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;
}

CodePudding user response:

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;
}

CodePudding user response:

Not an expert, but my guess is that your functions are just not being named by putting a function name without attribution. You should try:

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

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