search

Home  >  Q&A  >  body text

javascript - js type conversion

function a () {

}
a.toString = function(){
    console.log(1)
}
a.valueOf = function(){
    console.log(2)
}
a + '1' //2

Why only 2 is output? Shouldn't both 1 and 2 be output?

伊谢尔伦伊谢尔伦2791 days ago560

reply all(5)I'll reply

  • 我想大声告诉你

    我想大声告诉你2017-05-19 10:14:39

    Let me be more specific: generally only one of the two methods, valueOf and toString, can be called. Depending on the object type, there are different judgment orders. Specifically:
    1. If the object is to be converted into a string, it will first detect whether the object has a toString() method, call this and return the original value, and then convert the value into a string. If the object does not have a toString() method, or this method does not return a primitive value. Then js will detect whether the object has a valueOf() method, call it if it exists, also call and return the original value, and then convert this value into a string. If neither the object's valueOf nor toString methods exist, a TypeError exception will be thrown.
    2. If the object is to be converted into a number, it will detect whether it has a valueOf() method. If it does not detect the toString() method, the specific principle is the same as above.
    3. For all non-date objects, the conversion of objects to primitive values ​​is basically the conversion of objects to numbers, and all call valueof() first. If it is a date object, the conversion mode of object to string is used.
    Specific to your question, a is not a date object, so the valueof() method is called first. After successful conversion, the toString() method will naturally not be called again.

    reply
    0
  • 迷茫

    迷茫2017-05-19 10:14:39

    When running a+'1', only the a.valueOf method is called, and the toString method is not called. You can first understand the mechanism of toValueOf and toString methods

    reply
    0
  • 某草草

    某草草2017-05-19 10:14:39

    Problems with JS parsing mechanism

    reply
    0
  • PHPz

    PHPz2017-05-19 10:14:39

    Because this is the parsing mechanism of js, your use of "+" indicates the problem of using implicit conversion. If you do not have special provisions, js will automatically call the toString method such as conversion. If you write valueOf, it will be converted according to valueOf. Of course, toString has a higher priority

    reply
    0
  • ringa_lee

    ringa_lee2017-05-19 10:14:39

    When you do the addition operation, you will only call valueOf. Because it is not printed out, there is no need to convert it into a string, and of course toString will not be triggered.
    If you print it out like this, you can see that both methods will be called:

    console.log(a + '1');

    reply
    0
  • Cancelreply