Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

93
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda