I have a factory function, where I am returning a Book Object. When I create an object of the Book and change a field value, this is not reflected in the method of the Object. Any idea why this may be happening?
const Book = (title, author, pages, read) => {
const info = () => {
if (read == true) {
return `${title} by ${author} - ${pages} pages - already read`;
} else {
return `${title} by ${author} - ${pages} pages - not read yet`;
}
}
return { title, author, pages, read, info };
}
I create a Book Object using let book = Book(title, author, pages, read);
And change the value of read by accessing the read field directly.
However, when I change the value of read, this is not reflected in the info method.
CodePudding user response:
The object properties are not aliases for the variables, the variable values are used when creating the object.
To refer to the object properties, you need to use this.
And in order to have this refer to the object, you must use a traditional function rather than an arrow function.
const Book = (title, author, pages, read) => {
const info = function() {
if (this.read) {
return `${this.title} by ${this.author} - ${this.pages} pages - already read`;
} else {
return `${this.title} by ${this.author} - ${this.pages} pages - not read yet`;
}
}
return { title, author, pages, read, info };
}
let b = Book("Title", "Author", 10, false);
console.log(b.info());
b.author = "New Author";
console.log(b.info());
CodePudding user response:
In modern JS, you'd most probably want to use a class here which simplifies working with objects by alot:
class Book {
constructor(title, author, pages, read) {
this.title = title;
this.author = author;
this.pages = pages;
this.read = read;
}
get info() {
return `"${this.title}" by ${this.author} - ${this.pages} pages - ${this.read ? 'already read' : 'not read yet'}`
}
}
let b = new Book("No Place To Hide", "Glenn Greenwald", 259, false);
console.log(b.info);
b.author = "G. Greenwald";
console.log(b.info);
b.read = true;
console.log(b.info);
// you can even test if b is a Book:
// (which you could not with a factory function)
console.log(b instanceof Book);
