Christopher Altman
Christopher Altman

Reputation: 4896

Is there a consolidated way of writing several prototype functions for a single object?

I have about eight prototype functions for the Date object. I would like to avoid repeating Date.prototype. Is there a consolidated way of writing several prototype functions for a single object?

I tried this to no avail:

Date.prototype = {
  getMonthText: function(date){
    var month = this.getMonth();
    if(month==12) month = 0;
    return ['JAN','FEB','MAR','APR','MAY','JUN','JUL','AUG','SEP','OCT','NOV','DEC'][month];
  },
  getDaysInMonth: function(date){
    return 32 - new Date(this.getFullYear(), this.getMonth(), 32).getDate();
  }
};

Upvotes: 1

Views: 84

Answers (1)

Felipe
Felipe

Reputation: 1300

The way you are doing, you are replace the prototype with your new object.

If you use jQuery, it has a $.extend method that you could use like $.extend(Date.prototype, { getMonthText: function(date){...}, getDaysInMonth: function(date){...} })

If you dont use, you could easily create an extend like function with:

function extend(proto,newFunctions) {
   for (var key in newFunctions)
       proto[key] = newFunctions[key]
}

And call with:

extend(Date.prototype,{ getMonthText: function(date){...},  getDaysInMonth: function(date){...} });

Another way is just do it directly:

Date.prototype.getDaysInMonth = function(date){ ... }
Date.prototype.getMonthText = function(date){ ... }

I'd argue that this is more readable than the extend function.

Upvotes: 2

Related Questions