4
var a = "asd";
toString.call(a); //prints [object String]

Why does this not the same as a.toString();? The value of this within the toString function would be a in both cases right? I expected it output "asd" (same as a.toString()).

2 Answers 2

2

What you use is the window.toString, but it should be:

String.prototype.toString.call(a)  // then it should be same
Sign up to request clarification or add additional context in comments.

3 Comments

How is window.toString() different from String.prototype.toString()? Is there any documentation explaining the behavior of window.toString()?
They are just different implementations.
@xdazz - I believe toString in window has different native code than toString in String just like forEach in Array and Node List
0

They are different methods (although they have the same name). In addition to @xdazz's answer, to prove that toString behaves differently in other types:

[].toString.call("abc");  //Array

This will also not return "abc".


document.querySelectorAll("*").toString.call("abc")  //Node List

Not "abc".


(2).prototype.toString.call("abc")  //Number

Error, and also toString in Number also can have a radix argument.


Conclusion: They are all different. Since window is some kind of weird Object, it doesn't share the same toString as String's.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.