Leo Jiang
Leo Jiang

Reputation: 26145

How to change toString() for primitive types' implicit conversions in Javascript?

As an experiment, I did something like this:

Object.prototype.toString=function(){
  alert('works!');
}
'test'+{}; // alert is shown

However, this doesn't work for primitives:

Number.prototype.toString=function(){
  alert('works!');
}
'test'+123; // no alert
'test'+(new Number(123)); // no alert
(123).toString(); // yes alert

Is it possible for primitive implicit conversions to use a custom toString method?

Upvotes: 1

Views: 256

Answers (1)

Andy Ray
Andy Ray

Reputation: 32076

Under the hood, Javascript is calling .valueOf() first.

Number.prototype.valueOf = function(){ alert('works!'); }

This will alert because it's using the Number object:

'test'+(new Number(123))

This doesn't alert, I believe because 123 isn't getting autoboxed into a Number:

'test'+123

Javascript does have primitive types (aka an "unboxed" number, aka doesn't inherit from Object) but I don't believe you can modify those primitive prototypes. So no, you cannot overload pure primitive value functions.

Upvotes: 3

Related Questions