JavaScript笔记:封箱与开箱
包装器(wrapper)
1 var a = new String( "abc" ); 2 typeof a; // "object" ... not "String" 3 a instanceof String; // true 4 Object.prototype.toString.call( a ); // "[object String]" 5 console.log( s.toString() ); // "Hello World!"
内建原生类型函数(比如String()、Number()、Boolean()等)似乎可以用来构建原生值,但返回的实际上是一个包装后的原生值,一个对象。
内部[[class]](ES5)
typeof 返回值为"object"的值会被附加上[[class]]属性,比如上面第三行返回的[object String]。这个属性无法直接访问,但可以间接通过Object.prototype.toString.call(a)来间接展示。
1 Object.prototype.toString.call( [1,2,3] ); // "[object Array]",[[class]]是"Array" 2 Object.prototype.toString.call( /regex-literal/i ); // "[object RegExp]",[[class]]是"RegExp"
封箱包装器
如果对原生值访问属性或方法,比如str.length或者num.toString(),JS会自动对值进行封箱,以便访问。
手动封箱(不建议):
1 var a = "abc"; 2 var b = new String( a ); 3 var c = Object( a ); 4 5 typeof a; // "string" 6 typeof b; // "object" 7 typeof c; // "object" 8 9 b instanceof String; // true 10 c instanceof String; // true 11 12 Object.prototype.toString.call( b ); // "[object String]" 13 Object.prototype.toString.call( c ); // "[object String]"
开箱
使用valueOf()方法
1 var a = new String( "abc" ); 2 var b = new Number( 42 ); 3 var c = new Boolean( true ); 4 5 a.valueOf(); // "abc" 6 b.valueOf(); // 42 7 c.valueOf(); // true
也可以利用隐式类型转换:
1 var a = new String( "abc" ); 2 var b = a + ""; // `b` has the unboxed primitive value "abc" 3 4 typeof a; // "object" 5 typeof b; // "string"
来源:https://github.com/getify/You-Dont-Know-JS/blob/1ed-zh-CN/types%20%26%20grammar/ch3.md
浙公网安备 33010602011771号