简体   繁体   中英

How does toString() work in javascript?

"J" + { toString: function() { return "S"; } }; // "JS"

Why is the output "JS?"

When I do:

 "J" + { someFoo: function() { return "S"; } }; // "J[object Object]"

Why isn't this also "JS"?

I'm trying to figure out how the .toString() is getting used inside the first block.

Thanks

toString is a special function (in object's prototype), which is called when a stringified mode of the object is required.

In your cases, the addition operator calls the toString method of the object. From the specs :

  1. If Type(lprim) is String or Type(rprim) is String, then

    a. Return the String that is the result of concatenating ToString(lprim) followed by ToString(rprim).

However, this native method can be overridden, which you've done* in the first snippet. Addition operator just calls the custom method, which produces the result you've got.

In the latter snippet toString just returns a default value for objects.

You can see this happening in many situations, for example alert({}) calls internal toString method from object's prototype, since alert requires a string as an argument.

(* More accurate: you haven't re-written the native property, rather you've created an own property to the object with the same name, which is used instead of searching the native property from the prototype chain.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM