2011-02-08 18 views
1

我有約8個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(); 
    } 
}; 

回答

2

你正在做的樣子,你是更換原型的新對象。

如果你使用jQuery,它有,你可以使用像$.extend(Date.prototype, { getMonthText: function(date){...}, getDaysInMonth: function(date){...} })

如果你不使用$ .extend方法,你可以很容易地創建一個擴展喜歡與功能:

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){ ... } 

我認爲這比擴展函數更具可讀性。

+0

我認爲這在運行時效率較低。真的嗎? – 2011-02-08 15:25:57

相關問題