Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I add the method to Math in javascript

Tags:

javascript

I need a method in Math object of javascript which calculates the logarithm of any base. So basically what I did was this:

Math.log_b=function(b,x){return Math.log(x)/Math.log(b);}

What is the downside of extending built-in function like this?

To make my situation more clear, I am taking the user input and replacing it with appropriate Math object function names and passing it to eval for the calculation. If this is not clear, my dilemma is, in my case, I have to use eval (even if it is evil) and extending the Math object function best suits my case.

Is there possibility of some weird bugs or other when I extend the built-in function like this or is it the perfectly normal things to do?

like image 764
Jack_of_All_Trades Avatar asked Jul 26 '13 17:07

Jack_of_All_Trades


People also ask

How do you write a math function in JavaScript?

It can be written as: Math. pow(x, y), where x is a base number and y is an exponent to the given base.

How do you do addition in JavaScript?

Basic JavaScript Addition Add numbers in JavaScript by placing a plus sign between them. You can also use the following syntax to perform addition: var x+=y; The "+=" operator tells JavaScript to add the variable on the right side of the operator to the variable on the left.

How do you multiply in JavaScript?

The Multiplication Operator ( * ) multiplies numbers.


1 Answers

You should not modify what you don't own.

  • What happens if another plugin or 3rd party code you use adds their own version of log_b to Math, which provides a completely different signature?

  • What happen if a future version of JavaScript defines it's own version of log_b on Math?

Someone is going to cry, because for someone it wont do what they expect it to.


I'm not sure why extending Math best suits your case.

function my_log_b(b,x){return Math.log(x)/Math.log(b);}

... still seems to suit your case. Even better, define your own namespace, and put it in there;

var ME = {};

ME.log_b = function (b,x){return Math.log(x)/Math.log(b);}
like image 132
Matt Avatar answered Oct 24 '22 09:10

Matt