0

クラスが別のクラスからプロトタイプメソッドを継承し、継承するクラスで新しいプロトタイプメソッドを定義できるより良い方法はありますか?

var ParentConstructor = function(){
};

ParentConstructor.prototype = {
    test: function () {
        console.log("Child");
    }
};

var ChildConstructor = function(){
    ParentConstructor.call(this)
};

ChildConstructor.prototype = {

    test2: "child proto"
};

var TempConstructor = function(){};
TempConstructor.prototype = ParentConstructor.prototype;
ChildConstructor.prototype = new TempConstructor();
ChildConstructor.prototype.constructor = ChildConstructor;



var child = new ChildConstructor();

child.test();
console.log(child.test2)

console.log(child, new ParentConstructor());

test2からの継承を追加すると、プロトタイプのメソッド/プロパティが失われるため、これは機能しませんParentConstructor

他のクラスからいくつかのプロトタイプ props を持つクラスのプロトタイプ メソッドを拡張する他の方法を試しましたが、以前のメソッドを毎回オーバーライドしない方法が見つからなかったため、毎回失敗しました。

も試しましたvar Child = Object.create(Parent.Prototype)が、新しい小道具を定義すると、親の小道具が失われます。

4

2 に答える 2

2

のプロトタイプで新しいプロパティを定義する前に、継承を設定する必要がありますChildConstructor。また、新しいプロトタイプ プロパティを定義するときは、prototypeプロパティ全体をオーバーライドしないでください。代わりに、すでにプロパティで行ったように、新しいプロパティを簡単に追加できconstructorます。

ChildConstructor.prototype = new ParentConstructor();
ChildConstructor.prototype.constructor = ChildConstructor;

ChildConstructor.prototype.test2 = "child proto";
于 2013-08-13T19:56:13.483 に答える