Is it possible to write my own valueOf method for primitives in Javascript?

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? That is, is there a way to make a call to 'str'+123 alert() ?

+5
source share
1 answer

those. is there a way to make a call to 'str'+123 alert() ?

No, you need to do something to first push the primitive to its equivalent object, which this line does not (and I suppose you do not want to do this). The add operator (they call it that even when it is concatenated) will use the ToString specification an abstract operation to convert a number to a string. For numbers, the abstract ToString operation performs the following steps , which do not involve using any of the prototype Number or Object .


The abstract ToString operation applies to numbers :

  • If m is NaN , return the string "NaN" .
  • If m is +0 or -0 , return the string "0" .
  • If m is less than zero, return the String concatenation of the string "-" and ToString (- m ).
  • If m is infinity, return the string "Infinity" .
  • Otherwise, let n , k , and s be integers such that k ≥ 1, 10 <i> k 1s 10 k, the numerical value for s × 10 nk is m , and k is as small as possible. Note that k is the number of digits in the decimal representation of s , that s is not divisible by 10, and that the least significant digit s is not necessarily uniquely determined by these criteria.
  • If kn ≤ 21, return a string consisting of the digits k of the decimal representation s (in order, without leading zeros), followed by nk occurrences of the character 0 .
  • If 0 <n ≤ 21, return a string consisting of the most significant digits n, the decimal representation of s , followed by the decimal point ' . followed by the remaining kn digits of the decimal representation s .
  • If -6 <n ≤ 0, return a string consisting of the character ' 0 , and then the decimal point' . and then n occurrences of the character ' 0 , followed by the digits k of the decimal representation s .
  • Otherwise, if k = 1, return a string consisting of one digit s , and then a lowercase character ' e , followed by a plus sign' + or minus sign ' depending on whether n -1 is positive or negative followed by a decimal representation of the integer abs ( n -1) (without leading zeros).
  • Returns a string consisting of the most significant digit of the decimal representation s , followed by the decimal point '., Followed by the remaining k -1 digits of the decimal representation s , followed by the lowercase character' e , followed by the plus sign ' + or minus sign ' depending on whether n -1 is positive or negative, followed by a decimal representation of the integer abs ( n -1) (without leading zeros).
+3
source

All Articles