Skip to content

Instantly share code, notes, and snippets.

@clockworkgeek
Created July 17, 2014 13:12
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 clockworkgeek/e11c5964929f05dd01ab to your computer and use it in GitHub Desktop.
Save clockworkgeek/e11c5964929f05dd01ab to your computer and use it in GitHub Desktop.
Extending native Date using Prototype.js
/**
* Some built-in browser types cannot be subclassed normally.
* The following snippet demonstrates a perfect Date replacement.
*
* Example use:
* CustomDate = Class.create(BaseDate, {
* // custom methods here...
* });
*/
'use strict';
self.BaseDate = Class.create({ /** @memberOf BaseDate */
initialize: function(value) {
if (arguments.length < 1) value = Date.now();
else if (arguments.length > 1) value = Date.UTC.apply(null, arguments);
this.date = new Date(value);
},
// Firefox-only feature
__noSuchMethod__: function(name, args) {
return this.date[name].apply(this.date, args);
},
// need to override inherited methods which are not changed by magic method
toLocaleString: function() {
return this.date.toLocaleString();
},
toSource: function() {
return "(new BaseDate("+this.valueOf()+"))";
},
toString: function() {
return this.date.toString();
},
valueOf: function() {
return this.date.valueOf();
}
});
// Test for Firefox-only feature
try {
// Should do nothing if valid
({__noSuchMethod__:function(){}})._();
} catch(e) {
// If no magic method then only choice is to list every possible method
["getDate","getDay","getFullYear","getHours","getMilliseconds","getMinutes","getMonth",
"getSeconds","getTime","getTimezoneOffset","getUTCDate","getUTCDay","getUTCFullYear",
"getUTCHours","getUTCMilliseconds","getUTCMinutes","getUTCMonth","getUTCSeconds","getYear",
"setDate","setFullYear","setHours","setMilliseconds","setMinutes","setMonth","setSeconds",
"setTime","setUTCDate","setUTCFullYear","setUTCHours","setUTCMilliseconds","setUTCMinutes",
"setUTCMonth","setUTCSeconds","setYear","toDateString","toGMTString","toISOString","toJSON",
"toLocaleDateString","toLocaleFormat","toLocaleTimeString","toTimeString","toUTCString"]
.concat(Object.keys(Date.prototype)) // newly added methods
.each(function(name) {
BaseDate.prototype[name] = function() {
return this.date[name].apply(this.date, arguments);
};
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment