1

Javascript で OOP をよりよく理解しようとしています。以下の例と別の方法で create メソッドがどのように使用されているか説明してもらえますか? 私はそれを Web で調べ、SO に関するいくつかの投稿を確認しましたが、以下のコードで何が起こっているのかをまだしっかりと把握していません。私の理解を説明するためにコメントを提供しました。私が間違っているところを修正してください。

この例は、基本クラスのメソッドをオーバーライドするために使用されます。

// Defines an Employee Class
function Employee() {}

// Adds a PayEmployee method to Employee
Employee.prototype.PayEmployee = function() {
    alert('Hi there!');
}

// Defines a Consultant Class and
// Invokes the Employee Class and assigns Consultant to 'this' -- not sure and not sure why
// I believe this is a way to inherit from Employee?
function Consultant() {
    Employee.call(this);
}

// Assigns the Consultant Class its own Constructor for future use -- not sure
Consultant.prototype.constructor = Consultant.create;

// Overrides the PayEmployee method for future use of Consultant Class
Consultant.prototype.PayEmployee = function() {
    alert('Pay Consultant');
}
4

1 に答える 1

4

このコード:

function Consultant() {
    Employee.call(this);
}

Consultant コンストラクターが呼び出されたとき (つまり、Consultant のインスタンスが作成されたとき) に Employee コンストラクターを呼び出しています。Employee コンストラクターが何らかの初期化を行っている場合、コンサルタントの「サブタイプ」が作成されたときに呼び出されることが重要です。

このコード:

Consultant.prototype.constructor = Consultant.create;

はちょっと謎です。これは、コンサルタント関数オブジェクトのプロパティである create という名前の関数があることを意味します。ただし、投稿したコード サンプルには、そのようなプロパティはありません。undefined実際には、この行はConsultant コンストラクターに割り当てています。

あなたの質問は尋ねませんが、参考までに、 create 関数を使用したその行の代わりにおそらく必要なものは次のとおりです。

Consultant.prototype = new Employee();
Consultant.prototype.constructor = Consultant;

これがプロトタイプの継承パターンです。確かに、これが唯一の、または必ずしも最良のアプローチというわけではありませんが、私は気に入っています。

アップデート

Employee が引数を取る場合、次のように処理できます。

// Employee constructor
function Employee(name) {
    // Note, name might be undefined. Don't assume otherwise.
    this.name = name;
}

// Consultant constructor
function Consultant(name) {
    Employee.call(this, name);
}

// Consultant inherits all of the Employee object's methods.
Consultant.prototype = new Employee();
Consultant.prototype.constructor = Consultant;
于 2013-01-02T22:18:35.997 に答える