I\'m trying to subclass/extend the native Date object, without modifying the native object itself.
I\'ve tried this:
var util = require(\'util\')
Based on the answers by @sstur and its improvement by @bucabay:
Note that __proto__
is being used in those answers, which is deprecated and its use is strongly discouraged, at least according to the MDN docs.
Fortunately, it is possible to do what is desired without using __proto__
by setting each individual function from Date.prototype
in our class, which is simplified by making use of Object.getOwnPropertyNames().
function XDate() {
var x = new (Function.prototype.bind.apply(Date, [Date].concat(Array.prototype.slice.call(arguments))));
Object.getOwnPropertyNames(Date.prototype).forEach(function(func) {
this[func] = function() {
return x[func].apply(x, Array.prototype.slice.call(arguments));
};
}.bind(this));
this.foo = function() {
return 'bar';
};
}
A minor disadvantage of this method is that XDate
isn't actually a subclass of Date
. The check xdateobj instanceof Date
is false
. But this shouldn't be a worry as you can anyway use the methods of the Date class.