javascript: do primitive strings have methods?

╄→гoц情女王★ 提交于 2019-12-17 06:14:21

问题


MDN states:

primitive, primitive value

A data that is not an object and does not have any methods. JavaScript has 5 primitive datatypes: string, number, boolean, null, undefined. With the exception of null and undefined, all primitives values have object equivalents which wrap around the primitive values, e.g. a String object wraps around a string primitive. All primitives are immutable.

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


回答1:


No, string primitives do not have methods. As with numeric primitives, the JavaScript runtime will promote them to full-blown "String" objects when called upon to do so by constructs like:

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

In some languages (well, Java in particular, but I think the term is in common use) it's said that the language "boxes" the primitives in their object wrappers when appropriate. With numbers it's a little more complicated due to the vagaries of the token grammar; you can't just say

var foo = 27.toLocaleString();

because the "." won't be interpreted the way you'd need it to be; however:

var foo = (27).toLocaleString();

works fine. With string primitives — and booleans, for that matter — the grammar isn't ambiguous, so for example:

var foo = true.toString();

will work.




回答2:


The technically correct answer is "no".

The real-world answer is "no, but it will work anyway". That's because when you do something like

"s".replace()

the interpreter knows that you want to actually operate on the string as if you had created it with

var str = new String("s")

and therefore acts as if you had done that.



来源:https://stackoverflow.com/questions/5751704/javascript-do-primitive-strings-have-methods

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!