Why in Javascript is it possible to call String
as a function and also instantiating?
See 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 bit.
In the first result new String
is given as object
by typeof
. E String()
is given as string
.
But in practice, is there a difference between the two? I realize that they also have the same methods.
See:
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);
Note : We do not need to focus only on String
, since this is true for calls of Number
, Boolean
and Array
.