Get the App
SLTechnology News&Howtos  ›  Development  › 

What is the difference between valueOf and toString in js

Shulou Source: shulou.com Published: 2022-06-03 07:20:19 10月03日 Update

This article mainly shows you "what is the difference between valueOf and toString in js", the content is simple and clear, and I hope it can help you solve your doubts. Let the editor lead you to study and learn this article "what is the difference between valueOf and toString in js".

Both methods are the original methods of the object.

1. ValueOf is the original value of the object, and the call is usually not displayed. It is usually called automatically by js in the background.

2. One of the functions of toString itself is string conversion, which is also automatically converted.

3. If these two methods are overridden, valueOf will be called first during operation and toString will be called when displaying.

If only one method is overridden, the method is called first during operation and display.

Example

Var obj= {num:1,toString:function () {return this.num+1;}, valueOf:function () {return this.num+2;}} / / because num is referenced in valueOf, console.log (obj==2) will not be reclaimed by garbage collection mechanism; / / valueOf () / / alert (obj) should be called during operation; / / 2 browser pop-up window var obj= {num:1,toString:function () {return this.num+1;}, valueOf:function () {return this.num++ }} above is all the content of this article entitled "what's the difference between valueOf and toString in js". Thank you for reading! I believe we all have a certain understanding, hope to share the content to help you, if you want to learn more knowledge, welcome to follow the industry information channel!

Tags: Methods content articles operations primitive objects learning help functions background garbage characters strings examples easy to understand more mechanisms organization browsers knowledge Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno MariaDB MySQL OPPO Reno Linux Shulou Technology