0

Hello I'm wondering how to extends a constructor like Date, The thing is I have a large, very large application and I want to know each time a Date object is instanciated. Basically I want to print something in the constructor. I don't want to define a new construtor in which I would call Date() and then replace Date by the new constructor all over the code. I really want to extend Date. And I came up with this:

var previousPrototype = Date.prototype;
Date = function() {
 previousPrototype.constructor.call(this);
 console.log('new Date instanciation');
 }
Date.prototype = previousPrototype;

var extendedDate = new Date(); // prints 'new Date instanciation'

that seems good, but when I do extendedDate.getTime() for instance I get that sweet message

VM103:1 Uncaught TypeError: this is not a Date object.

I don't understand why it's not working, any help will be appreciated

Fanyo SILIADIN
  • 802
  • 5
  • 11
  • Date.prototype is no longer a "Date" object since ES6 came up on the stage. Helpful reference: http://www.ecma-international.org/ecma-262/6.0/#sec-object-internal-methods-and-internal-slots – Samuil Petrov Jun 21 '17 at 08:59

1 Answers1

0

The simplest solution may be this:

var previousDate = Date;
Date = function () {
    console.log(1);
    return new previousDate();
};
var extendedDate = new Date();
console.log(extendedDate.getTime());

Your function nether uses the keyword this nor return any object. You should first initialize the Date object and store it inot a variable. At the end of your function, you should return the object.

The example program is below:

var previousDate = Date;
Date = function() {
  var newDate = new previousDate();
  newDate.newproperty = true;
  return newDate;
}
// Date.prototype = previousPrototype;
var extendedDate = new Date();
console.log(extendedDate.getTime());
console.log(extendedDate.newproperty);

The above code is not good enough though. If you tried to add alert into the constructor function, you'll find that it is called multiple times in the current environment, but it will work in real environment:

var previousDate = Date;
Date = function() {
  var newDate = new previousDate();
  newDate.newproperty = true;
  alert("Called!");
  return newDate;
}
// Date.prototype = previousPrototype;
var extendedDate = new Date();
console.log(extendedDate.getTime());
console.log(extendedDate.newproperty);
attempt0
  • 639
  • 5
  • 14
  • hmm I understand your strategy, rebuild the constructor from an instance of Date, but I can't understand why what I did doesn't work since I execute previous in Date constructor, It should be just like editing Date constructor right? – Fanyo SILIADIN Jun 21 '17 at 12:46
  • @FanyoSILIADIN Please note that `this` in JavaScript is **not** a object, it is a keyword. You can't reference it outside. If you feel satisified with my answer, please remember to accept my answer. – attempt0 Jun 21 '17 at 14:28