Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

i dont know why the functions aren´t using my variable

i made a variable with a string inside, an then put that variable in two different functions. The problem here is that it shows me an error: "Uncaught ReferenceError: mostrarDatosTexto is not defined". I´m not sure enough why is this happening. Here´s the code:

const Libro = (titulo, autor) => {return(

    {
        autor: autor, 
        titulo: titulo,
        mostrarDatosTexto: `${titulo}, de ${autor.toUpperCase()}`,
        mostrarDatosEnConsola:  () => {return (console.log(mostrarDatosTexto))},
        mostrarDatosEnAlert:    () => {return (alert(mostrarDatosTexto))},
    }

)}


let unLibro = Libro('Ángeles y Demonios', 'Dan Brown')

console.log(unLibro)

unLibro.mostrarDatosEnConsola()
unLibro.mostrarDatosEnAlert()

i’ll really appreciate it if you can help me

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

mostrarDatosTexto is a property, not a variable. You need to access it using XXX.mostrarDatosTexto syntax.

Inside an object method, you can use this to refer to the object that the method was called on. But you have to use an ordinary function, not an arrow function, because arrow functions preserve the value of this from the scopre where they were defined, they don’t receive it as the method call contact.

console.log() and alert() don’t return anything, so there’s no point in using return to return their values. Just call them without using return.

const Libro = (titulo, autor) => {
  return (
    {
      autor: autor,
      titulo: titulo,
      mostrarDatosTexto: `${titulo}, de ${autor.toUpperCase()}`,
      mostrarDatosEnConsola: function() {
        console.log(this.mostrarDatosTexto);
      },
      mostrarDatosEnAlert: function() {
        alert(this.mostrarDatosTexto);
      },
    }
  )
}


let unLibro = Libro('Ángeles y Demonios', 'Dan Brown')

console.log(unLibro)

unLibro.mostrarDatosEnConsola()
unLibro.mostrarDatosEnAlert()
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading