2

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?

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.