Last active
April 28, 2016 10:05
-
-
Save fijiwebdesign/35ec423547cadf2632804d208e299dbe to your computer and use it in GitHub Desktop.
Extend native Date prototype without affecting the Date object
This file contains hidden or 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
// based on http://stackoverflow.com/a/30882416/255239 | |
function XDate() { | |
// create new Date() with passed in args | |
var date = new (Function.prototype.bind.apply(Date, [Date].concat(Array.prototype.slice.call(arguments)))) | |
date.__proto__ = XDate.prototype; // make XDate.prototype the inherited prototype of our Date instance. | |
return date; | |
} | |
XDate.prototype.__proto__ = Date.prototype; // inherit Date prototype so we can use Date methods | |
// example to show a new Date each time an instance is inspected | |
XDate.prototype.toString = function() { | |
return (new Date()).toString() | |
}; | |
// example | |
var date = new XDate() | |
setTimeout(function() { | |
console.log('Date string is now: ', date) // logs a date that is ~1 second apart, not the date when date was created | |
}, 1000) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment