Parasite Combination Inheritance: parent prototype's clone 如何包含子prototype's 属性 还没有赋值?

Parasite Combination Inheritance: How does parent prototype's clone consist child prototype's property which has not been assigned yet?

请查看 Nicholas C. Zakas 的书 Professional JS for Web Developers 中的代码片段:

function object(o){
  function F(){}
  F.prototype = o;
  return new F();
}

function inheritPrototype(subType, superType){
  var prototype = object(superType.prototype);
  console.log(prototype);
  prototype.constructor = subType;
  subType.prototype = prototype;
}

function SuperType(name){
  this.name = name;
  this.colors = [“red”, “blue”, “green”];
}

SuperType.prototype.sayName = function(){
  alert(this.name);
};

function SubType(name, age){
  SuperType.call(this, name);
  this.age = age;
}

inheritPrototype(SubType, SuperType);


SubType.prototype.sayAge = function(){
  alert(this.age);
};

在函数inheritPrototype() 中,我记录了变量原型。我看到 sayAge() 是 变量原型 的 属性。当我将 sayAge 属性 分配给对象 (supertype.prototype) 时,我不确定它是如何分配给原型的。此外,SubType.prototype.sayAge 在我调用函数 inheritPrototype 后正在初始化。所以我很困惑地看到原型有 sayAge 因为它是 属性.

https://jsfiddle.net/shettyrahul8june/ed22rrnj/

在 JSFiddle 运行 之后检查开发者控制台。谢谢

这就是控制台的工作原理。当您在大多数实现(尤其是浏览器实现)中使用 console.log 记录一个对象时,它会记录一个 reference 到该对象。当您稍后展开该对象时,您会看到它具有 then 的属性,而不是它在记录时所具有的属性。

如果我们记录对象具有的属性当您记录它时,我们可以看到它直到稍后才得到sayAge

function object(o) {
  function F() {}
  F.prototype = o;
  return new F();
}

function inheritPrototype(subType, superType) {
  var prototype = object(superType.prototype);
  showProps("in inheritPrototype", prototype);
  prototype.constructor = subType;
  subType.prototype = prototype;
}

function SuperType(name) {
  this.name = name;
  this.colors = [1, 2, 3];
}

SuperType.prototype.sayName = function() {
  alert(this.name);
};

function SubType(name, age) {
  SuperType.call(this, name);
  this.age = age;
}

inheritPrototype(SubType, SuperType);


SubType.prototype.sayAge = function() {
  alert(this.age);
};
showProps("after assigning sayAge", SubType.prototype);

function showProps(msg, obj) {
  var propNames = Object.keys(obj);
  console.log(msg, "count: " + propNames.length, propNames.join(", "));
}