3

コンストラクターを 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;
4

1 に答える 1

7

技術的にはそれを行う必要はありませんが、オブジェクト全体を置き換えるため、デフォルトでそこに配置され.prototypeている が失われる.constructorため、それに依存するコードがある場合は、手動で含める必要があります。

于 2012-11-04T20:44:24.280 に答える