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

Time:05-26

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

CodePudding user response:

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

  • Related