Can we say that String is an object in Javascript?

前端 未结 4 1181
春和景丽
春和景丽 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:05

    Strings are not objects, they are native types, like numbers, but if you want to access the method on it they are boxed with String object. The same happen with numbers you can call (10).toString() but in fact you're calling toString on Number instance that wraps 10, when you call the method.

    0 讨论(0)
  • 2021-01-19 05:05

    Every data type is a object in JavaScript. String, array, null, undefined . Everything is a object in JavaScript

    0 讨论(0)
  • 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
    
    0 讨论(0)
  • 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.

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