11
Why in Javascript it is possible to call String
as a function and also instantiating?
Take the example:
var str1 = new String(1)
var str2 = String(1)
console.log("Valor é %s e o tipo é %s", str1, typeof(str1));
console.log("Valor é %s e o tipo é %s", str2, typeof(str2));
I noticed that there is a small difference between one and the other, and it confused me a little.
In the first result new String
is given as object
for typeof
. And String()
is given as string
.
But in practice, is there a difference between the two? Because I see that they also have the same methods.
Behold:
var a = new String(1);
var b = String(2);
console.log(a.concat);
console.log(b.concat);
console.log(a.substr);
console.log(b.substr);
Observing: We don’t need to just focus on String
, since the same occurs with the calls of Number
, Boolean
and Array
.
It would be the same case as
int
andInteger
in Java– Guilherme Lautert
@Guilhermelautert exactly that.
– Maniero
Primitives have no properties but pretend to have methods:
console.log(TypeString.replace('á', 'é')); // olé
– bfavaretto