寄生虫组合继承:父原型的克隆如何包含尚未分配的子原型的属性?

ras*_*tay 1 javascript oop javascript-objects

请查看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);
};
Run Code Online (Sandbox Code Playgroud)

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

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

在JSFiddle中运行后检查开发人员控制台.谢谢.

T.J*_*der 5

这就是控制台的工作原理.当你登录一个对象console.log在大多数实现(特别是浏览器实现),它会记录一个参考对象.当你以后展开对象,你看到它具有的属性,然后,当你展开它,不是它有当它被记录下来.

如果我们记录对象在记录时所拥有的属性,我们可以看到它在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(", "));
}
Run Code Online (Sandbox Code Playgroud)