Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I override (or overwrite?) a built-in Javascript function

For unit-testing purposes, I need to overwrite the Number.prototype.toLocaleString() so that it is always called with en-US rather than default behavior. I understand overwriting a normal built-in function that receives a parameter, but toLocaleString() does not take the Number to convert to string directly as parameter so I am confused here.

I tried the following:

Number.prototype.toLocaleStringTest = Number.prototype.toLocaleString
Number.prototype.toLocaleString = function() { this.toLocaleStringTest('en-US') }

But the result of this new toLocaleString() function is always undefined. New function is certainly called, by the way, I ensured this via adding a temporary console.log("I am called!") in the implementation.

What am I doing wrong -- Or am I trying to achieve something that is not doable?

like image 364
schlingel Avatar asked Mar 05 '23 14:03

schlingel


1 Answers

You were very close... Only a return was missing... :-)

Number.prototype.toLocaleStringTest = Number.prototype.toLocaleString
Number.prototype.toLocaleString = function() {
  return this.toLocaleStringTest('en-US')
}
n = 123456.789;
console.log(n.toLocaleString());
like image 89
MarcoS Avatar answered Apr 08 '23 22:04

MarcoS