Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

92
Vistas
Function called inside an variable returns undefined

I am trying to get output from an function, where on calling it it should return John temp (2021) but am getting John undefined (undefined)

const user = {
    username : 'John',
    type: 'temp',
    yearJoin: 2021,
    userString(){
        function getUserDetails (){
            return `${this.type} (${this.yearJoin})`
        }
        return `${this.username} ${getUserDetails()}`;
    }
}
console.log(user.userString())

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

You need to set the scope of the getUserDetails call to this:

getUserDetails.call(this)

See:

const user = {
  username: 'John',
  type: 'temp',
  yearJoin: 2021,
  userString() {
    function getUserDetails() {
      return `${this.type} (${this.yearJoin})`
    }
    return `${this.username} ${getUserDetails.call(this)}`;
  }
}

console.log(user.userString());

You can clean this up, by moving the getUserDetails function up as a method on the object:

const user = {
  username: 'John',
  type: 'temp',
  yearJoin: 2021,
  getUserDetails() {
    return `${this.type} (${this.yearJoin})`
  },
  toString() {
    return `${this.username} ${this.getUserDetails()}`;
  }
}

console.log(user.toString());

Now take it one step further, as a class, and you have:

class User {
  constructor({ username, type, yearJoin }) {
    this.username = username;
    this.type = type;
    this.yearJoin = yearJoin;
  }
  getUserDetails() {
    return `${this.type} (${this.yearJoin})`
  }
  toString() {
    return `${this.username} ${this.getUserDetails()}`;
  }
}

const user = new User({
  username: 'John',
  type: 'temp',
  yearJoin: 2021
});

console.log(user.toString());

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda