【问题标题】:Parasite Combination Inheritance: How does parent prototype's clone consist child prototype's property which has not been assigned yet?寄生虫组合继承:父原型的克隆如何包含子原型尚未分配的属性?
【发布时间】:2016-07-19 14:18:41
【问题描述】:

请查看 Nicholas C. Zakas 的《Professional JS for Web Developers》一书中的代码 sn-p:

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)时,我不确定它是如何分配给原型的。此外,在我调用函数 inheritPrototype 之后,正在初始化 SubType.prototype.sayAge。所以我很困惑看到原型拥有 sayAge 作为它的属性。

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

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

【问题讨论】:

    标签: javascript oop javascript-objects


    【解决方案1】:

    这就是控制台的工作方式。在大多数实现(尤其是浏览器实现)中使用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(", "));
    }

    【讨论】:

    • 如果你想在准确的时间看到它,你需要做一个深度克隆并以某种方式打印出来。
    • 好的。感谢 T.J. 的解释
    猜你喜欢
    • 2019-11-18
    • 1970-01-01
    • 1970-01-01
    • 2023-03-16
    • 2016-02-15
    • 1970-01-01
    • 2015-01-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多