开发者

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

开发者 https://www.devze.com 2023-02-09 20:26 出处:网络
I have about eight prototype functions for the Date object. I would like to avoid repeating Date.prototype. Is ther开发者_StackOverflowe a consolidated way of writing several prototype functions for a

I have about eight prototype functions for the Date object. I would like to avoid repeating Date.prototype. Is ther开发者_StackOverflowe 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();
  }
};


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消