关于Boolean, Number, String

为了便于操作基本类型值,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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值