I am trying to make this code works properly:
class Reminder {
constructor(text) {
this.text = text;
}
remindMe(delay) {
setTimeout(function() {
console.log(`Your reminder after ${delay} seconds is: ${this.text}`);
}, delay * 1000);
}
}
//shows Reminder {text: "Hello World"}
const example = new Reminder("Hello world");
//shows undefined
console.log(example);
// shows "Your reminder after 3 seconds is: undefined"
console.log(example.remindMe(3));I have been without working with classes a lot of time, and I know is undefined because the method remindMe doesnt have access to the constructor, because it doesnt have a getter. But I have tried to create a getter and it didnt leave me to call it from the method remindMe, I tried to do something like this:
remindMe(delay) {
setTimeout(function () {
console.log(`Your reminder after ${delay} seconds is: ${getText()});
}, delay * 1000);
}
Any idea about where is the mistake? Thanks.
Advertisement
Answer
exampleis being logged in your code (as you can see from the snippet). It logs:{ "text": "Hello world" }remindMedoesn’t explicitly return anything so defaults toundefined(that’s the firstundefinedin your output). (Note: sinceremindMeis also a function containing a timeout it still wouldn’t work because you’re logging immediately, and the function only completes after three seconds. Plus it contains its ownconsole.logso there’s no need to log the result of calling the function anyway.)thiswon’t work as you want it to in thatsetTimeoutbecause the context has changed. Use an arrow function instead – they have nothisof their own and “borrow”thisfrom its outer lexical environment.
class Reminder {
constructor(text) {
this.text = text;
}
remindMe(delay) {
setTimeout(() => {
console.log(`Your reminder after ${delay} seconds is: ${this.text}`);
}, delay * 1000);
}
}
const example = new Reminder("Hello world");
console.log(example);
example.remindMe(3);