为了便于操作基本类型值,ECMAScript 还提供了3个特殊的引用类型:Boolean,Number,String
引用类型与基本包装类型的主要区别就是对象的生存期。使用new操作符创建的引用类型的实例,在执行流离开当前作用域之前都一直保存在内存中。而自动创建的基本包装类型的对象,则只存在于一行代码的执行瞬间,然后立即被销毁。这意味着我们不能再运行时为基本类型值添加属性和方法。
var s1 = "aaaa";
s1.name = "red";
console.log(s1.name); // undefined
console.log(s1 instanceof String); // false
console.log(typeof s1); // string
var s2 = String("aaaa");
s2.name = "red";
console.log(s2.name); // undefined
console.log(s2 instanceof String); //false
console.log(typeof s2); // string
var s3 = new String("aaaa");
s3.name = "red";
console.log(s3.name); // red
console.log(s3 instanceof String); //true
console.log(typeof s3); // object
var str1 = new String("str1");
str1.color = "red";
str2 = str1;
console.log(str2.color); // red
str1.color = "blue";
console.log(str2.color);// blue
str1 = new String("new str1");
console.log(str2.color); // blue
str1.color = "yellow";
console.log(str2.color); // blue
以上例子也适用于Boolean和Number