我通過創建一些對我有用的函數來擴展了javascript的核心功能。當爲今天的函數創建測試用例時,我開始想知道哪種方式最適合爲整數數字擴展javascripts功能。使用Number.prototype或Math對象。擴展javascript功能時,Number和Math函數有什麼區別?
Number.prototype.sqr = function() {
return this * this;
};
var test1 = (6).sqr();
alert("This is 36: " + test1);
OR
Math.sqr = function (num) {
return num * num;
};
var test2 = Math.sqr(6);
alert("This is 36: " + test2);
這兩個例子可以圍繞着爲您想創建任何整數類型的功能進行切換,所以應該使用哪個?