Uncaught Error on Class using new Date()

Uncaught Error on Class using new Date()
0

#1

Any method I add to the following class is giving me an uncaught error. Any hints appreciated! :grinning:

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!!


#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 :slight_smile:


#3

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.


#4

Since bday will reference the new date after the addDays method is called on it, you do not really need the return statement at then end of addDays. unless you were wanting to assign the returned value to another variable. But even then, it would just be a reference to the same date, so it does not seem to useful. This is just my 2 cents worth.


#5

Thanks @RandellDawson & @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 {…} ?


#6

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