Skip to content

Instantly share code, notes, and snippets.

@sstur
Last active August 29, 2015 14:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sstur/50bef66ad03262c4dc03 to your computer and use it in GitHub Desktop.
Save sstur/50bef66ad03262c4dc03 to your computer and use it in GitHub Desktop.
Extend (subclass) native Date
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)
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';
};
@sstur
Copy link
Author

sstur commented Jun 19, 2015

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?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment