【问题标题】:Object constructor points to the original constructor not prototype.constructor after redefining prototype of constructor function对象构造函数在重新定义构造函数原型后指向原来的构造函数而不是prototype.constructor
【发布时间】:2017-11-10 04:17:22
【问题描述】:

例如:

function F() {};
F.prototype = {
    test: function() { console.log('test'); }
};

console.log(F.prototype.constructor); // [Function: Object]

F.prototype = 'string';

var o = new F();
console.log(F.prototype.constructor); // [Function: String]
console.log(F.prototype);             // string
console.log(o.constructor);           // [Function: Object]

o.test();  // Can't work

在上面的代码中,初始构造函数是F(),即F.prototype.constructor。但后来我将F.prototype 重置为'string'。还有我的问题:

  1. F.prototype重置为'string'后,为什么F.prototype.constructor变成[Function: String]。换句话说,它决定了 F.prototype.constructor?
  2. 我知道新对象会继承prototype对象的属性,constructor属性也是如此。但是为什么对象p的构造函数是原来的构造函数[Function: Object],而不是[Function: String]呢?

提前致谢。

【问题讨论】:

标签: javascript oop constructor prototype


【解决方案1】:

构造函数字段没什么特别的,它和其他字段一样。

#1 的答案

F.prototype = "string";
console.log(F.prototype.constructor); // function String

记录function String,因为它与

console.log("string".constructor); // function String

#2 的答案

每个对象内部的__proto__ 字段必须是typeof x === "object"。在原型链的末尾总是有一个null 值(通常是Object.prototype.__proto__ 一个),并且不允许循环。您将原始string 分配给构造函数prototype 字段(typeof F.prototype === "string"),它不能用作__proto__,因此new 运算符只是回退以使用默认原型构造对象,即@ 987654333@.

【讨论】:

  • 好答案!谢谢!
  • 我想知道有没有办法打印构造函数的源代码,而不仅仅是它的类型[Function: Object]
  • @zhenguoli constructor.toString()
  • @Bergi,好的,我知道。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-10-07
  • 1970-01-01
相关资源
最近更新 更多