Tengo una función de fábrica, donde devuelvo un objeto de libro. Cuando creo un objeto del Libro y cambio un valor de campo, esto no se refleja en el método del Objeto. ¿Alguna idea de por qué puede estar pasando esto?
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 }; } Creo un objeto de libro usando let book = Book(title, author, pages, read); Y cambie el valor de lectura accediendo directamente al campo de lectura. Sin embargo, cuando cambio el valor de lectura, esto no se refleja en el método de información.
Las propiedades del objeto no son alias para las variables, los valores de las variables se utilizan al crear el objeto.
Para hacer referencia a las propiedades del objeto, debe usar this .
Y para que this se refiera al objeto, debe usar una función tradicional en lugar de una función de flecha.
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());En JS moderno, lo más probable es que desee utilizar una class aquí que simplifica mucho el trabajo con objetos:
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);