【问题标题】:Why is Number.prototype a Number为什么 Number.prototype 是一个数字
【发布时间】:2012-05-10 14:33:15
【问题描述】:
({}).toString.call(Number.prototype) === "[object Number]"

Number 原型对象本身就是一个 Number 对象(它的 [[Class]] 是“Number”),其值为 +0。

15.7.4

为什么Number.prototype 是一个数字会有用? (对于将 [[Class]] 设置为非 Object 的所有其他内置原型也是如此)

我之所以选择Number.prototype,是因为我可以想象Array.prototypeDate.prototype 的合理遗留原因。

【问题讨论】:

  • +1 我总是喜欢奇怪的 JavaScript 问题。
  • 我们应该有一个wtfjs标签:)
  • 不确定这就是评论的原因。 Number.prototype 覆盖了特殊的 valueOf 方法以生成数字,因此 Number.prototype 的原始形式是数字。拥有Number.prototype 的行为就像一个原始包装器 w.r.t. valueOf 但有 [[class]] object 会很奇怪。
  • @ŠimeVidas 使用“JavaScript”标签是多余的。
  • @MikeSamuel “是 Number.prototype 是一个具有函数属性的对象,还是一个应该明智地表现出对 valueOf 调用等的对象”之间的区别是一个很好的观点。让它成为答案

标签: javascript ecmascript-5


【解决方案1】:

Number 原型对象本身就是一个 Number 对象(它的 [[Class]] 是“Number”),其值为 +0

为什么Number.prototype 不是数字对象?它的[[Prototype]]是Object.prototype,所以还是继承自Object。

【讨论】:

  • 因为每隔一个数字都满足typeof n === "number"n instanceof Number。它不应该是一个数字,就像 Function.prototype 不应该是一个函数
  • typeof 不只是简单地回显[[Class]](例如typeof Array == 'object'),而且instanceof Number 仅在Number.prototype[[Prototype]] == Number.prototype 时才为真。我想你可以看到其中的困难。
  • 我的意思是所有其他数字要么是一个数值,要么是通过new Number 创建的。 Number.prototype 很奇怪
【解决方案2】:

一般来说,Constructor.prototypeConstructor 定义的“类型”的一个范例。尽管对于不可变的原语来说事情似乎变得很棘手,尤其是当你涉及到拳击的东西时,这个示例概念仍然有意义,0Number 的“示例”。

【讨论】:

    猜你喜欢
    • 2015-01-22
    • 2013-06-17
    • 2013-11-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-04
    • 1970-01-01
    • 2021-02-24
    相关资源
    最近更新 更多