我有大约八个Date对象的原型函数。我想避免重复Date.prototype
。是否有为单个对象编写多个原型函数的综合方法?
我试过这个无济于事:
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();
}
};
答案 0 :(得分:2)
您正在做的方式是用新对象替换原型。
如果您使用jQuery,它有一个$ .extend方法,您可以使用$.extend(Date.prototype, { getMonthText: function(date){...}, getDaysInMonth: function(date){...} })
如果您不使用,可以使用以下方法轻松创建类似函数的扩展:
function extend(proto,newFunctions) {
for (var key in newFunctions)
proto[key] = newFunctions[key]
}
并致电:
extend(Date.prototype,{ getMonthText: function(date){...}, getDaysInMonth: function(date){...} });
另一种方法是直接进行:
Date.prototype.getDaysInMonth = function(date){ ... }
Date.prototype.getMonthText = function(date){ ... }
我认为这比扩展功能更具可读性。