I am trying to create and object that inherits from the Date object.
Below is a Firebug transcript of what I am trying to do.
>>> date_son = Object.create( Date )
Function {}
>>> typeof date_son
"object"
>>> date_son.gettime
undefined
>>> date_son.prototype.getTime
getTime()
I use Object.create to create an object date_son which inherits from Date. The getTime function/attribute is available on date_son.protype, but not on the date_son object itself.
I am clearly doing something wrong. Can anyone point me in the right direction on how to create an object that inherits from Date so that date_son.getTime() is available on the date_son object.
I do not wish to extend Date directly, because I think messing/changing globals is bad programming practice.
There is a note on the MDN Docs by Mozilla (https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Date):
Note: Note that Date objects can only be instantiated by calling Date or using it as a constructor; unlike other JavaScript object types, Date objects have no literal syntax.
Object.create
expects an instance when a parameter is given. Date
is no instance on its own and will therefore not work with Object.create.
Furthermore, to address your issue with extending Date directly:
Extending native objects is something which is done regularly. MooTools does it for instance with their own .implement
method:
https://github.com/mootools/mootools-more/blob/master/Source/Types/Date.js#L55
Tutorial about extending natives:
http://net.tutsplus.com/tutorials/javascript-ajax/quick-tip-how-to-extend-built-in-objects-in-javascript/
Edit:
And an article about the presumed evils of extending natives: http://perfectionkills.com/extending-built-in-native-objects-evil-or-not/
You could do this:
var date_son = Object.create( Date.prototype );
but it wouldn't seem to do much good because you'll be calling those methods on something other than a Date
.
console.log( date_son.getTime() ); // won't work
You could call it like this, but I don't know why you'd want to:
var date_son = Object.create( Date.prototype );
var new_date = new Date();
console.log( date_son.getTime.call( new_date ) ); // 1313964470748
If you want to add some Date utilities, and you don't want to extend Date.prototype
, then just create a library of methods that accept a Date
object.
var date_son = {
some_method: function( d ) {
// do something with the date
return d;
}
};
var date = date_son.some_method( new Date );
Good news! This works with the new class-based syntax introduced in ES5.
class DateSon extends Date {
equals(other) {
if (typeof other === "object") {
return this.getTime() === other.getTime();
} else {
return false;
}
}
copy() {
return new Date(this.getTime());
}
}
dateSon1 = new DateSon();
dateSon2 = dateSon1.copy();
dateSon2.setDate(dateSon1.getDate() + 1);
console.log(dateSon1.equals(dateSon2));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With