JavaScript的装箱与拆箱
我们通常认为对象才具有属性和方法,但当我们使用字符串或某些数据类型时却可以直接调用它的某些方法和属性:
let str = 'This is a string.'
console.log(str.length);//17
let num = 20.05
console.log(num.toFixed(1));//20.1
为了更为方便的操作和使用原始值,ES 为布尔值、数值、字符串提供了各自的引用类型———Boolean、Number、String。
装箱
当用到某个原始值的属性或方法时,会自多年后创建一个相应的原始值包装对象,这称之为装箱。
装箱的步骤
- 创建一个包含了原始值包装对象类型的实例
- 调用实例上特定的方法
- 销毁该实例
该实例被使用后马上销毁,因此不得访问到该实例
拆箱
使用valueOf( )进行拆箱
let str = new String('This is a string.')
console.log(str);//String {"This is a string."}
console.log(str.valueOf(str));//This is a string.
当使用new关键字创建时,若要获得该原始值,则需要拆箱操作来实现。