Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

94
Views
La función llamada dentro de una variable devuelve indefinido

Estoy tratando de obtener resultados de una función, donde al llamarla debería devolver John temp (2021) pero estoy obteniendo a 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 answers
Answer question

0

Debe establecer el alcance de la llamada getUserDetails a this :

 getUserDetails.call(this)

Ver:

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

Puede limpiar esto moviendo la función getUserDetails como un método en el objeto:

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

Ahora dé un paso más, como clase, y tendrá:

 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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!