开发者

When extending javascript functionality, what is the difference between Number and Math function?

开发者 https://www.devze.com 2023-02-18 02:20 出处:网络
I have extended javascripts core functionality by creating a few functions that were useful to me. When creating test cases for a function today I started wondering which way is the best to extend jav

I have extended javascripts core functionality by creating a few functions that were useful to me. When creating test cases for a function today I started wondering which way is the best to extend javascripts functionality for integer numbers. Using Number.prototype, or the Math object.

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);

These two examples could be switched around for any integer type function that you would like to create, so which should be used?


I 'd go with Math.sqr, because it doesn't force the reader of the code to think "what is this thing that has an sqr member?". Of course in a real program you wouldn't see (6).sqr() which might make it clearer what is going on, but rather some variable.


Doesn't really matter, whatever syntax you prefer. That's not case when you start messing with Array.prototype or (GASP) Object.prototype.

Simply for consistency, I prefer to modify Math since other things like pow, sqrt, sin, etc are in there.

0

精彩评论

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

关注公众号