How to add method to math in javascript

I need a method in a javascript Math object that computes the logarithm of any base. So basically I did this:

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

What is the disadvantage of extending the built-in function?

To make my situation clearer, I take user input and replace it with the corresponding function names of the Math object and passing it to eval for calculation. If this is not clear, my dilemma, in my case, I must use eval (even if it is evil), and the extension of the function of the Math object is best suited for my case.

Is there the possibility of some strange errors or others when I extend the built-in function, for example, or are these absolutely normal things?

+6
source share
2 answers

You must not change what you do not have.

  • What happens if another plugin or third-party code that you use adds its own version of log_b to Math , which provides a completely different signature?

  • What happens if a future version of JavaScript defines its own version of log_b on Math ?

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


I'm not sure why the Math extension is best suited to your case.

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

... seems to suit your case. Better yet, define your own namespace and place it there;

 var ME = {}; ME.log_b = function (b,x){return Math.log(x)/Math.log(b);} 
+6
source

You can prototype it:

 if (Math.__proto__) { Math.__proto__.log_b=function(b,x){ return this.log(x) / this.log(b); } } else { alert('Cannot prototype `Math`'); } 

But this is probably not the best idea that you can rewrite your browser code.

It is better to add this method to the object that you yourself created.

0
source

Source: https://habr.com/ru/post/950378/


All Articles