构造函数.原型不在原型链中

Constructor.prototype not in the prototype chain?

本文关键字:原型 构造函数      更新时间:2023-09-26

related:关于原型链、原语和对象的混淆

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

我认为这应该打印true

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规范:

当以参数V调用isPrototypeOf方法时,将采取以下步骤:

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

基本数严格来说不是对象。

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

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

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

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

显然JavaScript在某个地方决定原语也可以是对象。

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