Can we say that String is an object in Javascript?

前端 未结 4 1182
春和景丽
春和景丽 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条回答
  •  旧时难觅i
    2021-01-19 05:26

    It's true that everything in JavaScript is just like object because we can call methods on it. When we use new keyword with string it becomes an object otherwise it's primitive type.

    console.log(typeof new String('str')); //object
    console.log(typeof 'str'); //string

    Now whenever we try to access any property of the string it box the the primitive value with new String()

    'str'.indexOf('s')
    

    is equivalent to

    (new String(str)).indexOf('s').
    

    The above process is called as "Boxing". "Boxing" is wrapping an object around a primitive value.

提交回复
热议问题