我不需要使用Math.round功能,如果它不允許我選擇我想要的小數位數。所以我創建了我使用的以下函數。可以覆蓋默認的Math.round javascript功能嗎?
Number.prototype.round = function(precision) {
var numPrecision = (!precision) ? 0 : parseInt(precision, 10);
var roundedNum = Math.round(this * Math.pow(10, numPrecision))/Math.pow(10, numPrecision);
return roundedNum;
};
我的問題是,我可以改變它,而不會有任何影響。
Math.roundP = function(num, precision){
var pow = Math.pow(10, precision||0);
return (Math.round(num*pow)/pow);
};
我意識到這會覆蓋默認的Math.round功能,但是我不需要它。這在Javascript中可以嗎?我之前沒有這樣做過,所以我只想看看人們對此的看法。或者,對我來說可能更好,讓它保持原樣。
我無法決定何時使用Number.prototype以及何時使用Math。
好點...謝謝!那麼什麼時候使用Math以及什麼時候使用Number是個好時機?我應該在數字中使用數字嗎? – Metropolis 2011-03-22 03:07:50
@Metropolis,我會建議對於在任何核心對象中放置任何方法都非常謹慎。 – 2011-03-22 03:10:48
我是....我幾乎不使用它們,我可能有6個功能?除此之外,我還沒有遇到任何我需要放在這裏的人。但對於我所擁有的人來說,我希望他們能夠在最好的地方。 – Metropolis 2011-03-22 03:11:54