Doubt regarding the extension of the Date object

Asked

Viewed 29 times

1

I’m having a problem whose cause I can’t identify.

I have the following builder:

class ExtDate extends Date {
    constructor () {
        super();
    }

    foo() {
        console.log('bar');
    }
}

Theoretically it should do exactly the same thing as the builder Date, only with the function foo().

I have the following function:

function ext(obj) {
    //Retorna uma string com o nome do construtor do parametro
    let constr = obj.constructor.toString().replace('()', '').split(' ')[1]; 

    construtores = {
        'Date' : ExtDate
    }

    return new construtores[constr](obj);
}

So far so good. If I insert a date object into this function it returns me an almost equal date object. The question is: why? See:

var a = new Date('02-25-2019'); //Mon Feb 25 2019 00:00:00 GMT-0300 (Horário Padrão de Brasília)
var b = ext(a); //Mon Feb 25 2019 12:46:41 GMT-0300 (Horário Padrão de Brasília)
var c = new Date(a); //Mon Feb 25 2019 00:00:00 GMT-0300 (Horário Padrão de Brasília)
var d = new ExtDate(a); //Mon Feb 25 2019 12:46:41 GMT-0300 (Horário Padrão de Brasília)

In short, my class ExtDate is creating times with the time of the browser, while the original constructor returns with the hours 00 always. Even when I enter a value of a date object with 00 hours, it returns me the current time.

Why does this occur, and how do I fix this problem and similar ones that might appear?

class ExtDate extends Date {
  constructor() {
    super();
  }

  foo() {
    console.log('bar');
  }
}

function ext(obj) {
  //Retorna uma string com o nome do construtor do parametro
  let constr = obj.constructor.toString().replace('()', '').split(' ')[1];

  construtores = {
    'Date': ExtDate
  }

  return new construtores[constr](obj);
}

var a = new Date('02-25-2019'); //Mon Feb 25 2019 00:00:00 GMT-0300 (Horário Padrão de Brasília)
var b = ext(a); //Mon Feb 25 2019 12:46:41 GMT-0300 (Horário Padrão de Brasília)
var c = new Date(a); //Mon Feb 25 2019 00:00:00 GMT-0300 (Horário Padrão de Brasília)
var d = new ExtDate(a); //Mon Feb 25 2019 12:46:41 GMT-0300 (Horário Padrão de Brasília)

console.log(a);
console.log(b);
console.log(c);
console.log(d);

1 answer

3


Because the builder of ExtDate always calls the empty Date constructor.

class ExtDate extends Date {
  constructor () {
    super();
  }

  foo() {
    console.log('bar');
  }
}

var extDate = new ExtDate('2019-01-01');
console.log(extDate);

class ExtDate extends Date {
  constructor (param) {
    super(param)
  }
}

console.log(new ExtDate('2019-01-01'))
console.log(new ExtDate(new Date()))

  • Got it. In case I extend an object that receives multiple parameters, I can do constructor(...param) { super(...param) } or need to specify parameter per parameter?

  • Probably the signature needs to be identical.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.