Search code examples
javascriptprototype-programming

Is it possible to apply a callback function to "new Date" using prototype


I want to add 1 hour to every Date it created using prototype and now I got this:

Date.prototype.addOneHr = function (){
    this.setTime(this.getTime()+1*1000*60*60);
}

However, I have to call it every new Date():

var date=new Date();
data.addOneHr();

It is very inconvenient and it gives me more mess. D:
So I am thinking that if there is a way to call addOneHr() every time I created a new Date, so that it won't give me headaches when editing the JavaScript.

Any solutions are welcomed. Thanks.


Solution

  • You can't do what you're asking, but you could make it a little better by altering your function slightly:

    Date.prototype.addOneHr = function() {
      this.setTime(this.getTime() + 1000 * 60 * 60);
      return this;
    }
    

    By having it return the object, you can write code like this:

    var a_date = new Date().addOneHr();