通过提示将保存在数组中的数据与类链接并用方法显示(console.log (information ()
class Libro {
constructor(titulo, autor, año, genero) {
this.titulo = titulo
this.Autor = autor
this.Año = año
this.Genero = genero
}
informacion() {
return console.log(`El libro ${this.titulo} del autor ${this.Autor} fue publicado en el año ${this.Año} y es de genero ${this.Genero}`);
}
}
let titulo1 = prompt('Introduce el titulo del libro')
let autor1 = prompt('Introduce el autor del libro')
let año1 = prompt('Introduce el año en que fue publicado el libro')
let genero1 = prompt('Introduce el genero literario del libro')
let libro1 = [titulo1, autor1, año1, genero1];
libro1.push(new Libro(titulo, autor, año, genero))
console.log(libro1.informacion());发布于 2021-01-24 01:36:02
类标识符引用类构造函数。
替换
let libro1 = [titulo1, autor1, año1, genero1];
libro1.push(new Libro(titulo, autor, año, genero))
console.log(libro1.Libro());使用
let libro1 = new Libro(titulo, autor, año, genero)
libro1.informacion() // call the informacion method of libro1它创建类实例对象,将其分配给libro1,然后调用libro1的informacion方法。
如果您想要一个图书对象数组,可以将libro1 (和其他书籍)保存在一个数组中:
const libri = [];
... // create libro1
libri.push(libro1);
... // create libro2
libri.push( libro2);若要创建多本书,请尝试将提示放入返回Libro类对象的函数中。这样,所有书籍都会使用相同的提示集。
作为对注释的响应,informacion方法已经调用console.log并返回undefined (如果这是console.log返回的内容)。返回信息字符串可能更适合您的目的:
informacion() {
return `El libro ${this.titulo} del autor ${this.Autor} fue publicado en el año ${this.Año} y es de genero ${this.Genero}`;
}如果将提示的结果保存在数组中,如
let arr = [titulo, Autor, Año, Genaro];您可以使用rest parameter syntax将它们传递给构造器函数。
let libro = new Libro( ...arr );https://stackoverflow.com/questions/65866263
复制相似问题