为什么Object.getPrototypeOf(instance.constructor)不等于instance.constructor.prototype?

时间:2018-08-07 06:59:13

标签: javascript ecmascript-6 prototype

标题说明了一切,但代码如下:

class A {}
class B extends A {}

const b = new B()


Object.getPrototypeOf(b.constructor) === b.constructor.prototype // false

Object.getPrototypeOf(b.constructor) === A // true
b.constructor.prototype === A // false. why?

我的意思是,上面的代码是违反直觉的。为什么这样做呢?

2 个答案:

答案 0 :(得分:2)

  

__proto__prototype不同。

假设您有一个对象obj。现在,obj.prototype实际上不会像您期望的那样为您提供obj的原型。要获得obj的原型,您必须做obj.__proto__。运行以下代码,您将得到答案。另外,阅读this可以进一步了解__proto__prototype之间的区别。 :)

class A {}
class B extends A {}

const b = new B()

console.log(Object.getPrototypeOf(b.constructor) === b.constructor.__proto__) // true
console.log(Object.getPrototypeOf(b.constructor) === A) // true
console.log(b.constructor.__proto__ === A) // true

答案 1 :(得分:1)

在您的代码中:

b.constructor.prototype === A; // false

这是错误的,因为b的原型是A的原型,而不是A本身。起初听起来可能会造成混淆,所以我在下面留下一个示例:

class A {}
class B extends A {}

const b = new B()


Object.getPrototypeOf(b.constructor) === b.constructor.prototype // false

Object.getPrototypeOf(b.constructor) === A // true
b.constructor.prototype === A // false. why?

console.dir(b.constructor.__proto__ === A); // true

在此示例中的最后一条语句:

console.dir(b.constructor.__proto__ === A); // true

b的__proto__属性实际上是指同一个对象A。

您可能还会发现以下有趣的内容:

class A {}

console.log(typeof A); // constructors are merely masked functions with added functionality

console.log(typeof A.__proto__);  // constructors inherit from the Function object

console.log(typeof A.__proto__.__proto__); // the Function object inherits from Object object