其中JS有 6 种原始类型:number、string、boolean、null、undefined和Symbol7 种类型object。
原始类型没有自己的属性和方法,但是,类型具有number包装对象,这些对象具有许多预定义的属性和方法,可以简化使用这些数据类型的工作。当访问实际值的方法时,后者可以临时转换为适当的包装对象,如构造函数,或充当具有属性和方法的对象。stringbooleannew String()new Number()new Boolen()
我不明白为什么在直接对值和存储原始值的变量调用方法时都会创建类型string和包装器,但前提是在变量而不是值上调用方法时。booleannumber
例子:
const str = 'hello world'
str.toString() // => "hello world"
'hello world'.toString() // => "hello world"
const bool = true
bool.toString() // => "true"
true.toString() // => "true"
const num = 5
num.toString() // => "5"
5.toString() // => Uncaught SyntaxError: Invalid or unexpected token
