javascript - js type conversion
伊谢尔伦
伊谢尔伦 2017-05-19 10:12:39
0
5
494
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?

伊谢尔伦
伊谢尔伦

小伙看你根骨奇佳,潜力无限,来学PHP伐。

reply all(5)
我想大声告诉你

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.

迷茫

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

某草草

Problems with JS parsing mechanism

PHPzhong

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

左手右手慢动作

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');
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!