This question has come out of another, which concerns the behaviour of console.dir
with string literals. In particular, see the comments on my answer.
As we all know, String
objects in JavaScript have a number of methods. Those methods are defined on the String.prototype
object. String.prototype.toUpperCase
for example. We can therefore do things like this:
var s = new String("hello"),
s2 = s.toUpperCase(); //toUpperCase is a method on String.prototype
However, we can also do this:
var s = "hello", //s is a string literal, not an instance of String
s2 = s.toUpperCase();
Clearly, the JavaScript interpreter is doing some form of conversion/cast when you call a method of String.prototype
on a string literal. However, I can't find any reference to this in the spec.
It makes sense, because otherwise you'd have to explicity cast every string literal to a String
object before you could use any of the methods, and that would be quite annoying.
So my question is, where is this functionality described, and am I right in assuming the literal value is temporarily cast to an instance of String
? Am I over-thinking this and missing something obvious?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…