JS基础篇:5、包装类型

1,015 阅读1分钟

背景

上一文中我们提到了基本数据类型不能添加属性和方法也就是说基本类型不存在属性和方法;但是字符串、数字、布尔值都能够调用属性和方法,例如:

const str = '123';
console.log(typeof(str)); // string
console.log(str.toString()); // 123
console.log(str.length); // 3
const num = 123console.log(typeof(num)); // number
console.log(num.toString()); // 123
const bool = true;
console.log(typeof(bool)); // boolean
console.log(bool.toString()); // true

可以看出上述三种Number、String、Boolean类型能调用方法,跟我们认知的有差入。那这又是为啥呢?向下看。

定义

JS数值、字符串、布尔值分别相对应的Number、String、Boolean三个原生对象。这三个原生对象把原始类型的值变成(包装成)的对象。也就是原始类型的包装对象

var str = new String('asd'); // String {"asd"}
var num = new Number('123'); // Number {123}
var bool = new Boolean(true); // Boolean {true}

console.log(typeof(str)) // object
console.log(typeof(num)) // object
console.log(typeof(bool)) // object

str === 'asd' // false
num === 123 // false
bool === true // false

上面代码,基于原始类型的值,生成了三个对应的包装对象。可以看到,str、num、bool都是对象,且与对应的原始类型值不相等。

自动转换

在Number、String、Boolean类型调用属性或方法的时候JavaScript 引擎自动将其转为包装对象,在这个对象上调用其属性或方法。调用结束后,这个临时对象就会被销毁。这就叫原始类型与实例对象的自动转换。

总结

这三个对象(Number、String、Boolean)作为构造函数使用(带有new)时,可以将原始类型的值转为对象;作为普通函数使用时(不带有new),可以将任意类型的值,转为原始类型的值。