Constructor.prototype不在原型链中?

时间:2013-03-29 13:53:28

标签: javascript prototype

相关:Confusion about protype chain , primitives and objects

在Firebug控制台中:

a = 12
a.constructor.prototype.isPrototypeOf(a) // prints 'false'

我认为这应该打印true

2 个答案:

答案 0 :(得分:9)

a = 12创建一个原始数字,它与Number对象不完全相同。为了属性访问的目的,隐式地将基元强制转换为对象。

a = 12; //a is a primitive
b = new Number(12); //b is an object
a.constructor.prototype.isPrototypeOf(a); //false because a is primitive
b.constructor.prototype.isPrototypeOf(b); //true because b is an object

根据ECMAScript spec

  

使用参数 V 调用isPrototypeOf方法时,将执行以下步骤:

     
      
  1. 如果 V 不是对象,请返回false
  2.   

原始数字严格来说不是对象。

答案 1 :(得分:0)

a = new Number(12);
a.constructor.prototype.isPrototypeOf(a) // prints 'true'

我不够聪明地告诉你为什么我只知道它是这样的。是的,这很奇怪。

现在,你可以说12是一个原语,而new Number(12)是一个对象”。但你怎么解释这个?

(12).toFixed(3); // "12.000"

显然某处JavaScript正在决定原语也可能是一个对象。

为什么存在这种区别?你如何在两种形式之间转换?这对性能有何影响?所有与此问题相关的问题我都没有答案。