[removed] do primitive strings have methods?

前端 未结 2 1540
日久生厌
日久生厌 2020-11-28 13:09

MDN states:

primitive, primitive value

A data that is not an object and does not have any methods. JavaScript has 5 primitive datatypes: string, n

相关标签:
2条回答
  • 2020-11-28 13:24

    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.

    0 讨论(0)
  • 2020-11-28 13:48

    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.

    0 讨论(0)
提交回复
热议问题