我創建了這個函式,它應該創建/回傳一個具有自定義原型和基本屬性的物件。問題是當我嘗試從物件的原型呼叫方法時,我得到錯誤:不是函式。我的猜測是可能與this
關鍵字有關,但我不確定。為什么會發生這種情況,我該如何解決?
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;
}
uj5u.com熱心網友回復:
分配一個新物件來book
替換現有值。它不會與您在那里的物件合并。
您需要一一分配新的屬性值。
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;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/513970.html
上一篇:如何映射未知物件鍵的陣列