Javascript: do primitive strings have methods?

MDN :

primitive, primitive meaning

Data that is not an object and does not have any methods. JavaScript has 5 primitive data types: string, number, boolean, null, undefined. With the exception null and undefined, all primitive values ​​have object equivalents that are primitive values, for example. a String object wraps a string primitive. All primitives are immutable.

Therefore, when we call "s".replace or "s".anything , it is equivalent to new String("s").replace and new String("s").anything ?

+6
source share
2 answers

No, string primitives have no methods. As with numerical primitives, the JavaScript runtime will push them to full-blown String objects when invoking constructs such as:

 var space = "hello there".indexOf(" "); 

In some languages ​​(well, in particular, in Java, but I think this term is generally accepted), he said that the language “puts” primitives in its object wrappers when necessary. With numbers, this is a little more complicated due to the vagaries of the grammar of the marker; you can't just say

 var foo = 27.toLocaleString(); 

because "." will not be interpreted as you need; However:

 var foo = (27).toLocaleString(); 

works great. With string primitives —— and boolean, for that matter; grammar is not ambiguous, therefore, for example:

 var foo = true.toString(); 

will work.

+12
source

Technically, the answer is no.

The real answer is no, but it will work anyway. This is because when you do something like

 "s".replace() 

the interpreter knows that you want to actually work with the string, as if you created it with

 var str = new String("s") 

and therefore acts as if you did.

+4
source

Source: https://habr.com/ru/post/886445/


All Articles