The inheritance from Date class

Posted on
  • What is the reason that I can't inherit from Date class?
    The short example is here:

    The constructor of AppDate uses the constructor of Date class, but the last one doesn't create an 'ms' field! There is only an additional field 'reference' created by AppDate constructor.
    In addition there are no methods of Date class in AppDate class.
    Why?

  • I don't have time to look into this right now I'm afraid...

    However when you post code up, please can you do it as text so I can copy/paste and test?

  • var
         dStr   = '2014-08-24T09:14',
         time, timeIhn;
    
    //own date&time class
    function AppDate() {
       Date.apply(this, arguments);
       this.reference = Date.now();
    }
    
    AppDate.prototype = Object.create(Date.prototype);
    
    //main
    time = new Date(dStr);
    timeIhn = new AppDate(dStr);
    
    print('The initial class time is ', time.toString());
    print('The inherited class time is ', timeIhn.toString());
    
  • I just did a quick check and pasted this into node.js (changing print to console.log) and I get:

    > time = new Date(dStr);
    Sun Aug 24 2014 10:14:00 GMT+0100 (BST)
    > timeIhn = new AppDate(dStr);
    { reference: 1408962782458 }
    
    > console.log('The initial class time is ', time.toString());
    The initial class time is  Sun Aug 24 2014 10:14:00 GMT+0100 (BST)
    
    > console.log('The inherited class time is ', timeIhn.toString());
    TypeError: this is not a Date object.
    

    So presumably the code you've used isn't correct... For starters, Date(...) returns a date object, but you're throwing it away after apply.

    In Espruino, you can make your code work with:

    function AppDate() {
       var d = Date.apply(this, arguments);
       d.reference = Date.now();
       return d;
    }
    

    But node.js still won't work, which isn't a good sign. Maybe someone else has some ideas?

  • Mmm... What about methods? I'd like to have methods of Date class in my new AppDate...

    The way of inheritance that I 've used works good with another classes but not with Date. I woudn't like to build bulky functions to copy objects from Date to new class :-)

    And one more question: how can I change the time zone?

  • Is there a reason you wouldn't just extend Date itself via Date.prototype?

    I'm afraid right now you can't change timezone of the date - so you'd have to add or subtract the relevant amount of hours manually.

  • I think, it'll be simpler to include a Date object as a component in new class that I can extend as I wish.

    Although by inheritance it would be more beautiful

    I've spied in your code the time zone is GMT+0100(BST). It's interesting how have you set it?

  • Post a reply
    • Bold
    • Italics
    • Link
    • Image
    • List
    • Quote
    • code
    • Preview
About

The inheritance from Date class

Posted by Avatar for Uhv @Uhv

Actions