浅谈包装对象


摘自·JavaScript权威指南

何为包装对象?

答:在存取对字符串,数字,布尔值的属性时临时创建的对象叫包装对象。

  包装对象只是被看做是一种实现细节,而不会特别的关注。字符串,数字,布尔值的属性都是可读的,不能定义新属性。它只是偶尔用来区分字符串值和字符串对象,数字值和数字对象,布尔值和布尔对象。

1 var a = 'string';
2 a.max = 0;
3 console.log(a.max); // undefined
4 var b = a.max;
5 console.log(b); // undefined

想修改包装对象的属性要用到构造函数来显式的创建包装对象

例如:

1 var a = 'string' , b = 1 , c = true;
2 var A = new String(a) , B = new Number(b) , C = new Boolean(c) ;
3 A.max = 12;
4 B.min = 0;
5 C.center = true6 console.log(A.max, B.min, C.center); // 12, 0, true
7 console.log(A == a, A === a, B == b, B === b); // true,false
View Code
1 1 var a = 'string' , b = true, c = 12;
2 2 var A = new String(a), B = new Boolean(b), C = new Number(c);
3 3 A == a // true;
4 4 A === a // false;
5 5 A.max = 'STRING' ;

"==" 原始值和包装对象是相等的 "==="  比较的是地址 数据类型

原文地址:https://www.cnblogs.com/xiaxuening/p/9870921.html