Creé una función constructora y algunos objetos que se insertan en una matriz.
Desde aquí, necesito llamar a una función en estos objetos en una matriz que genera una interfaz html básica. Creé la función de constructor y la tengo funcionando en su mayoría, sin embargo, sigo recibiendo un error en las herramientas de desarrollo que indica que mi método this.render() que se muestra a continuación no es una función.
Puedo hacer que esto funcione cuando intento simplemente consolar. registrar los objetos en la matriz (con un bucle), pero no puedo superar este error de no poder usar el método render(). Cualquier ayuda sería apreciada. Código a continuación. Tenga en cuenta que el objetivo final es tener la información procesada adjunta a un div con id de "salida". Gracias
function ArtistType(name, genre, albums) { this.name = name; this.genre = genre; this.albums = albums; this.publishAlbum = function () { this.albums++; }; this.render = function () { const artistName = document.createElement("h2"); artistName.innerText = this.name; const genre = document.createElement("div"); genre.innerText = this.genre; const albums = document.createElement("div"); albums.innerText = this.albums; document.getElementById("output").appendChild(artistName, genre, albums) }; } let artists = []; const artist1 = new ArtistType("Black Sabbath", "metal", 0) const artist2 = new ArtistType("Huey Lewis and the News", "rock", 0) const artist3 = new ArtistType("Beastie Boys", "hip hop", 0) artists.push(artist1, artist2, artist3); artist1.publishAlbum(); //below some of what I have tried... //artists.forEach(this.render()) //have also tried for...in loop and others...example: //for (var i = 0; i < artists.length; i++) { // this.render(); }
<html> <head> <title>Test</title> </head> <body> <h1>Name will go here</h1> <!-- Output the content --> <div id="output"></div> <!-- Link the script --> <script src="scripts.js"></script> </body> </html>
Tienes que referirte a un objeto en particular para usar su función render()
. Algo como esto:
function ArtistType(name, genre, albums) { this.name = name; this.genre = genre; this.albums = albums; this.publishAlbum = function () { this.albums++; }; this.render = function () { const artistName = document.createElement("h2"); artistName.innerText = this.name; const genre = document.createElement("div"); genre.innerText = this.genre; const albums = document.createElement("div"); albums.innerText = this.albums; document.getElementById("output").appendChild(artistName, genre, albums) }; } let artists = []; const artist1 = new ArtistType("Black Sabbath", "metal", 0) const artist2 = new ArtistType("Huey Lewis and the News", "rock", 0) const artist3 = new ArtistType("Beastie Boys", "hip hop", 0) artists.push(artist1, artist2, artist3); artist1.publishAlbum(); //below some of what I have tried... //artists.forEach(this.render()) //have also tried for...in loop and others...example: for (var i = 0; i < artists.length; i++) { artists[i].render(); }
<div id="output"></div>
this
solo existe dentro de la función, no puedes usarlo mágicamente fuera de ella Prueba esto:
artists.forEach(artist => artist.render())
o
for (const artist of artists) { artist.render() }
Al acceder a una matriz en un bucle for, debe usar una anotación entre corchetes y un índice: artists[i].render();
. En mi ejemplo, en realidad usé forEach
para mostrarle otra forma de bucle. Puede hacer referencia a esta documentación para saber más sobre forEach
.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach
A menos que necesite admitir navegadores antiguos, podría considerar usar clases. Las clases también ayudan a simplificar un poco el código y pueden facilitar el acceso a los objetos. Más en línea con otros lenguajes orientados a objetos.
Finalmente, tenga en cuenta que estoy usando append
en lugar de appendChild
. append
le permite pasar múltiples nodos y los agrega todos. Sin embargo, no es compatible con IE. appendChild
solo agregará el primer nodo que pase.
class Artist { constructor(name, genre, albums) { this.name = name; this.genre = genre; this.albums = albums; } publishAlbum() { this.albums++; } render() { const artistName = document.createElement("h2"); artistName.innerText = this.name; const genre = document.createElement("div"); genre.innerText = this.genre; const albums = document.createElement("div"); albums.innerText = this.albums; document.getElementById("output").append(artistName, genre, albums) } } let artists = [new Artist("Black Sabbath", "metal", 0), new Artist("Huey Lewis and the News", "rock", 0), new Artist("Beastie Boys", "hip hop", 0) ]; artists[0].publishAlbum(); artists.forEach(function(artist) { artist.render(); });
<div id="output"></div>