I'm trying to subclass/extend the native Date object, without modifying the native object itself.
I've tried this:
var util = require('util');
function MyDate() {
Date.call(this);
}
util.inherits(MyDate, Date);
MyDate.prototype.doSomething = function() {
console.log('Doing something...');
};
var date = new MyDate();
date.doSomething();
console.log(date);
console.log(date.getHours());
and this:
function MyDate() {
}
MyDate.prototype = new Date();
MyDate.prototype.doSomething = function() {
console.log("DO");
}
var date = new MyDate();
date.doSomething();
console.log(date);
In both cases, the date.doSomething()
works, but when I call any of the native methods such as date.getHours()
or even console.log(date)
, I get 'TypeError: this is not a Date object.'
Any ideas? Or am I stuck to extending the top-level Date object?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…