首页 > 解决方案 > 为什么日志中的 F.prototype 属性不一致

问题描述

所以函数是对象类型的,所以可以有属性。默认情况下,函数 F 将具有名称、长度和原型属性,并且原型属性将默认设置为一个对象,该对象具有一个指向函数本身的键“构造函数”。IE

function F() {
  this.foo = "bar";
}

/* default prototype
F.prototype = { constructor: F};
*/

这可以通过运行console.log(Object.getOwnPropertyDescriptors(F.prototype));哪些输出来证明

 {
    constructor: {
        value: [Function: F],
        writable: true,
        enumerable: false,
        configurable: true
    }
 } 

并且F.prototype.constructor == F评估为真。

令人困惑的是,它console.log(F.prototype);只会输出一个空对象F {}

同样console.log(Object.getOwnPropertyDescriptors(F));会产生以下内容:

{
length: { value: 0, writable: false, enumerable: false, configurable: true },
  name: {
    value: 'F',
    writable: false,
    enumerable: false,
    configurable: true
  },
  prototype: {
    value: F {},
    writable: true,
    enumerable: false,
    configurable: false
  }
}

F {}为什么当我期望类似的东西时这些返回一个空对象{ constructor: [Function: F] }

标签: javascriptfunctionprototypal-inheritancepropertydescriptor

解决方案


推荐阅读