Can we say that String is an object in Javascript?

前端 未结 4 1180
春和景丽
春和景丽 2021-01-19 04:24

I\'m always confused when I hear strings are primitives in JS, because everybody knows that string has different methods like: length, indexOf, search etc.

l         


        
4条回答
  •  南笙
    南笙 (楼主)
    2021-01-19 05:18

    Not certainly in that way.

    If you try to use a class method for a primitive, the primitive will be temporarily wrapped in an object of the corresponding class ("boxing") and the operation will be performed on this object. For example,

    1..a = 2;
    

    It's equal to:

    num = new Object(1.);
    num.a = 2;
    delete num;
    

    So, after executing the operation, the wrapper will be destroyed.

    However, the primitive itself will remain unchanged:

    console.log( 1..a ) // undefined
    

提交回复
热议问题