Reputation: 2244
"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
Upvotes: 1
Views: 957
Reputation: 23396
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:
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.
Upvotes: 4