为什么即使 "read" 字段发生变化,"info()" 也不起作用?

Why does "info()" not work even though the "read" field changes?

我有一个工厂函数,我在其中返回一个 Book 对象。当我创建 Book 的对象并更改字段值时,这不会反映在对象的方法中。知道为什么会这样吗?

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

我使用 let book = Book(title, author, pages, read); 创建了一个 Book 对象 并通过直接访问读取字段来更改读取的值。 但是,当我更改 read 的值时,这并没有反映在 info 方法中。

对象属性不是变量的别名,创建对象时使用变量值。

要引用对象属性,需要使用this

并且为了 this 引用对象,您必须使用传统函数而不是箭头函数。

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());

在现代 JS 中,您很可能想在此处使用 class,这大大简化了对对象的处理:

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