JavaScript 基础:基本类型和引用类型

160 阅读1分钟

JavaScript的基本类型包括 undefined, null, string, number, symbol, boolean, bigint。引用类型只有一种 object

下面以string类型为例说明基本类型和引用类型的使用:

string基本类型可以使用字面量或String全局对象生成

字面量

> str = "abc"
'abc'
> typeof str
'string'
>

String()

> str = String('abv')
'abv'
> typeof str
'string'
>

不使用 new 关键字的String(),生成的是基本类型变量,使用 new 关键字生成的是引用类型变量

> String('abc') === 'abc'
true
> new String('abc') === 'abc'
false
>

基本类型的变量调用方法时,编译器会自动隐式创建一个临时的对象类型

> str = "abc"
'abc'
> str.toString = () => 'aaa';    
[Function (anonymous)]
> str
'abc'
> str.toString()
'abc'
>

str.toString = () => 'aaa'; 等价于 new String(str).toString = () => 'aaa';

因此程序执行完,并不会改变 变量 str。