简体   繁体   中英

How can I add the method to Math in 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?

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

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 it is probably not the best idea in that you could be overwriting browser code.

Better to add this method to an Object you made yourself.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM