【问题标题】:Why do you need to reset javascript constructor during inheritance?为什么在继承期间需要重置 javascript 构造函数?
【发布时间】:2012-11-04 20:43:18
【问题描述】:

为什么将构造函数从 Mammal 重置为 Cat 很重要?我一直在玩这个代码,并没有发现使用“错误”构造函数的任何负面影响。

function Mammal(name){
    this.name=name;
    this.offspring=[];
}

Cat.prototype = new Mammal();        // Here's where the inheritance occurs
Cat.prototype.constructor=Cat;       // Otherwise instances of Cat would have a constructor of Mammal

function Cat(name){
    this.name=name;
}

例如:

function Mammal(name){
    this.name=name;
    this.offspring=[];
}

Cat.prototype = new Mammal();        // Here's where the inheritance occurs


function Cat(name){
    this.name=name;
    this.hasFur = true;
}

c1 = new Cat();
alert(c1.hasFur); //returns true;

【问题讨论】:

    标签: javascript constructor


    【解决方案1】:

    从技术上讲,您不需要 这样做,但是由于您要替换整个 .prototype 对象,因此您将丢失默认放置在那里的 .constructor,所以如果您有依赖它的代码,你需要手动包含它。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多