Magno Alberto
Magno Alberto

Reputation: 668

Javascript: Overriding Date - How get value that was passed to the constructor

I'm studying and also wanting to extend Date Object, and one of the thing that I like, is being able to access the value that was passed in the constructor in my prototype. The goal is to change the value depending on some criteria that I will be establishing as soon as I can 'intercept' the value.

In this example I would like to be able to access the value "2019-03-31" that was passed during the new Date().

I know there is the Moment JS and that maybe it does what I need ... but my goal is study for future use of 'prototype'.

Date.prototype.myTest = function myTest() {

  let datetime = this;

  return 'ok';

};
let dt = new Date("2019-03-31").myTest();

Upvotes: 0

Views: 539

Answers (2)

Federico Galfione
Federico Galfione

Reputation: 1109

I'm sorry but as you can see from Date documentation the string passed as parameter to the constructor is not saved. You can access only to some getter and setter methods to modify the Date. So in your function you can rebuild the date in a specific format that you like, but not retrieve the original string.

The only way to solve your problem is by using ES6 and extending the Date class.

class TestDate extends Date{
    constructor(date){
        super(date)
        this.const_date = date  // save input
    }
    myTest() {
        return this.const_date;
    };
}


console.log((new TestDate("2019-04-16")).myTest())

Upvotes: 0

Mark
Mark

Reputation: 92460

If you want to extend the Date object, a very simple way is to use ES6 classes with extend. It's easier and is probably a better idea than trying to modify the built-in date constructor. In the constructor you can do whatever you like including saving the original input for later or immediate use:

class myDate extends Date{
    constructor(d){
        super(d)
        this.originalInput = d  // save input
    }
    myTest() {
        console.log("original input:",  this.originalInput);
        return 'ok';
      };
}

let dt = new myDate("2019-03-31")
// log the original input:
dt.myTest();

// you can still use `Date` methods:
console.log(dt.toDateString())


let badDate = new myDate("what should I do with bad input")
badDate.myTest();
console.log("Date string:", badDate.toDateString())

Upvotes: 1

Related Questions