← 中文资源

简体中文版本

装箱包装对象与原始值不同

原始值通过临时装箱获得方法,但 new 出来的包装是对象:typeof 变成 object、严格相等失配,valueOf 才取到底层值,Symbol 干脆拒绝 new。

阅读英文原文

运行结果

以下输出由构建管线在沙箱中真实运行该示例捕获。

typeof text : string
typeof boxed: object
strict equal: false
loose equal : true
primitive methods: HELLO 5
valueOf equal: true
boxed number: object true true
new Symbol throws: TypeError

实现说明

顶层就这几处状态:text、boxed。

使用要点

  • 跑完文件,输出里会留下标记——typeof text :、typeof boxed:、strict equal:。

常见问题

需要安装第三方包吗?

不需要。只使用语言和平台的内建 API,粘贴进项目即可使用,无需安装任何东西。 跨调用保留的状态放在这些顶层绑定里:text、boxed。

核心语句

const boxed = new String('hello');
const n = new Number(7);
const text = 'hello';

代码示例

// Primitives are values; wrappers created with new are objects that box them.
const text = 'hello';
const boxed = new String('hello');

console.log('typeof text :', typeof text);
console.log('typeof boxed:', typeof boxed);
console.log('strict equal:', text === boxed);
console.log('loose equal :', text == boxed); // wrapper unwraps via valueOf

// Primitives get wrapper methods through temporary boxing, then let go.
console.log('primitive methods:', text.toUpperCase(), text.length);

// Explicit unwrapping compares the real value underneath the wrapper.
console.log('valueOf equal:', text === boxed.valueOf());

// new Number and new Boolean box the same way.
const n = new Number(7);
console.log('boxed number:', typeof n, n instanceof Number, n.valueOf() === 7);

// Symbol refuses new: there is no wrapper form for it.
try {
  new Symbol('x');
} catch (error) {
  console.log('new Symbol throws:', error.constructor.name);
}