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