Any method I add to the following class is giving me an uncaught error. Any hints appreciated!
class NewDate {
constructor(date){
this.date = new Date(date);
return this.date;
}
addDays(num){
let result = this.date;
result.setDate(result.getDate() + num);
return result;
}
}
let bday = new NewDate('02/20/1983');
bday.addDays(5); // // Uncaught TypeError: bday.addDays is not a function
If I write the function using dot notation directly on the class object, it works fine.
bday.setDate(bday.getDate() + 10);
Thanks!!
Layer
September 18, 2018, 6:26am
2
let result = this.day;
This is a typo i guess, it should be this.date
^^
Commenting the return
statement in the constructor should fix the code
1 Like
Thanks for the typo catch, I fixed it in the OP. Unfortunately, still have the same issue.
In fact, I can’t seem to add any method to this class at all.
class NewDate {
constructor(date){
this.date = new Date(date);
return this.date;
}
// addDays(num){
// let result = this.date;
// result.setDate(result.getDate() + num);
// return result;
// }
method1(){
return true;
}
}
bday.method1(); // Uncaught TypeError: bday.method1 is not a function
really puzzling and frustrating.
Thanks @camperextraordinaire & @Layer . I’m getting closer!
class NewDate {
constructor(date){
this.date = new Date(date);
}
addDays(num){
let result = this.date;
result.setDate(result.getDate() + num);
}
}
let bday = new NewDate('02/20/2018');
console.log(bday);
bday.addDays(10);
console.log(bday);
//Console output:
//NewDate {date: Tue Feb 20 2018 00:00:00 GMT-0800 (Pacific Standard Time)}
//NewDate {date: Fri Mar 02 2018 00:00:00 GMT-0800 (Pacific Standard Time)}
It seems to be calculating correctly, but shouldn’t the console output show something like bday {…} ?
1 Like
The object you created is of the class NewDate, not bday, bday is just an arbitrary identifier you’ve given to one instance of NewDate
1 Like