Basic JavaScript types include undefined, NULL, String, number, symbol, Boolean, bigint. There is only one object reference type.
The following uses string as an example to illustrate the use of primitive and reference types:
String primitives can be generated using literals or string global objects
literal
> str = "abc"
'abc'
> typeof str
'string'
>
Copy the code
String()
> str = String('abv')
'abv'
> typeof str
'string'
>
Copy the code
String(), which does not use the new keyword, generates primitive-type variables, while using the new keyword produces referential variables
> String('abc') = = ='abc'
true
> new String('abc') = = ='abc'
false
>
Copy the code
When a primitive type variable calls a method, the compiler automatically implicitly creates a temporary object type
> str = "abc"
'abc'
> str.toString = () => 'aaa';
[Function (anonymous)]
> str
'abc'
> str.toString()
'abc'
>
Copy the code
str.toString = () => ‘aaa’; Equivalent to new String(STR).toString = () => ‘aaa’;
So when the program finishes, it doesn’t change the variable STR.