Number.prototype.valueOf=function(){
alert('works!');
}
'str'+123; // no alert
'str'+(new Number(123)); // alert
Is there a way to write custom valueOf() methods for primitives? I.e. is there a way to make 'str'+123 call alert()?
I.e. is there a way to make
'str'+123callalert()?
No, you have to do something to promote the primitive to its equivalent object first, which that line doesn't do (and I take it you don't want to do). The addition operator (they call it that even when it's concatenation) will use the spec's ToString abstract operation to convert the number to a string. For numbers, the ToString abstract operation does the steps below, which don't involve using anything from the Number or Object prototype.
The ToString abstract operation applied to numbers:
"NaN"."0"."-" and ToString(−m)."Infinity".0’..’, followed by the remaining
k−n digits of the decimal representation of s.0’, followed by a
decimal point ‘.’, followed by −n occurrences of the character
‘0’, followed by the k digits of the decimal representation of s.e’, followed by a plus sign ‘+’ or minus sign
‘−’ according to whether n−1 is positive or negative, followed by the
decimal representation of the integer abs(n−1) (with no leading zeroes).e’, followed by a plus sign
‘+’ or minus sign ‘−’ according to whether n−1 is
positive or negative, followed by the decimal representation of the integer abs(n−1) (with no leading zeroes).If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With