Last active
August 29, 2015 14:23
-
-
Save sstur/50bef66ad03262c4dc03 to your computer and use it in GitHub Desktop.
Extend (subclass) native Date
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var date = new MyDate(2015, 5, 18) | |
console.log(date instanceof Date) //true | |
console.log(date instanceof MyDate) //true | |
console.log(Object.prototype.toString.call(date)) //[object Date] | |
console.log(date.foo()) //bar | |
console.log('' + date) //Thu Jun 18 2015 00:00:00 GMT-0700 (PDT) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function MyDate(a, b, c, d, e, f, g) { | |
var date; | |
switch (arguments.length) { | |
case 0: | |
date = new Date(); | |
break; | |
case 1: | |
date = new Date(a); | |
break; | |
case 2: | |
date = new Date(a, b); | |
break; | |
case 3: | |
date = new Date(a, b, c); | |
break; | |
case 4: | |
date = new Date(a, b, c, d); | |
break; | |
case 5: | |
date = new Date(a, b, c, d, e); | |
break; | |
case 6: | |
date = new Date(a, b, c, d, e, f); | |
break; | |
default: | |
date = new Date(a, b, c, d, e, f, g); | |
} | |
// note: use `Object.setPrototypeOf` instead of __proto__ to be truly standards-compliant | |
date.__proto__ = MyDate.prototype; | |
return date; | |
} | |
MyDate.prototype.__proto__ = Date.prototype; | |
MyDate.prototype.foo = function() { | |
return 'bar'; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This approach seems to be the best of the various workarounds I've seen (wrapping
Date
class, creating class with similar API, etc). It works in IE9+ and all modern JS engines including Node (basically any JS engine that supports modifying the proto chain). Anyone see any drawbacks to this approach?