如果您查看 ECMAScript 3 规范,您将看到原始值类型 Null 和 Undefined 没有伴随的 Null 和 Undefined 对象。
>> Null
ReferenceError: Null is not defined
其他原始值类型 Number、String 和 Boolean 类型确实有伴随的 Number、String 和 Boolean 对象,您可以从全局范围引用它们。
>>Number
function Number() { [native code] }
>>Boolean
function Boolean() { [native code] }
这些原始值类型的目的是为它们各自的原始值类型提供诸如toString
和 的方法valueOf
:
>>var n = 1;
>>n.toString();
"1"
是相同的
>>var n = 1;
>>Number.prototype.toString.call(n);
"1"
布尔值和字符串也可以这样工作:
>>var b = true;
>>b.toString();
"true"
>>Boolean.prototype.toString.call(b);
"true"
当您尝试混合类型时,您可以看到原始值对象正在使用其随附对象的方法:
>>Boolean.prototype.toString.call(n);
TypeError: Boolean.prototype.toString is not generic
>>Number.prototype.toString.call(b)
TypeError: Number.prototype.toString is not generic
有趣的是,对于布尔和字符串文字类型,您可以直接从文字中调用这些方法:
>>true.toString();
"true"
>>Boolean.prototype.toString.call(true)
"true"
>>"moo".toString();
"moo"
>>String.prototype.toString.call("moo")
"moo"
原始值 null 和 undefined,因为它们没有伴随的 Null 和 Undefined 对象不能做这些事情:
>>Null
ReferenceError: Null is not defined
>>null.toString()
TypeError: Cannot call method 'toString' of null
原始值类型 number 的行为类似于两者的混合。toString
如果直接使用 Number 的原型对象的方法,则可以调用文字:
>>Number.prototype.toString.call(1);
"1"
但是您不能像使用字符串和布尔值一样从文字本身访问该方法:
>>1.toString()
SyntaxError: Unexpected token ILLEGAL
为什么即使有 Number 对象,数字文字的行为也与布尔值和字符串不同?