Wrapper for default date constructor in JavaScript?
I would like a kind of wrapper for the default Date
object in JavaScript so that whenever I have something like var a = new Date();
, I want to execute some particular code in the constructor.
I basically want to 开发者_JAVA技巧have my own Date class that needs to be invoked whenever a call is made to Date()
rather than the native code.
You need to save the reference for the native Date
object, than make your own wrapper, which invokes the native Date
then mutates it, or adds additional behavior.
var OldDate = Date;
var Date = function() {
var that = new OldDate();
that.mystuff = 5;
// do other things with the date
// and execute your own things
// ...
return that;
}
var now = new Date();
alert(now.mystuff);
However, I wouldn't mess with native objects.
精彩评论