2
function Parent (arg1, arg2) {

    alert(arg1);

    this.member1 = arg1;
    this.member2 = arg2;
};

Parent.prototype.update = function () {

    // parent method update
};

function Child (arg1, arg2, arg3) {

    Parent.call(this, arg1, arg2);
    this.member3 = arg3;
};

Child.prototype = new Parent;

Child.prototype.update = function () {

    // overwritten method update
};

function init () {

    var childObject = new Child(false, false, false);
    childObject.update();
}

結果は、次の 2 つのアラートです。

  1. 未定義
  2. 間違い

アラートが 2 回発生するのはなぜですか? すでに検索しましたが、まだ何も見つかりません + 何を検索すればよいかわかりません。

結果は「false」の 1 つのアラートになるはずですが、間違っていますか?

ありがとう!

4

2 に答える 2

4

のコンストラクターを使用しParentてのプロトタイプを作成することによりChild、コンストラクターが呼び出されます。これは、の最初のアラートですundefined

同じプロトタイプチェーンを使用しているが、プロトタイプの作成時に親コンストラクターを呼び出さないプロトタイプを作成するには、その間に別のステップを追加する必要があります。

Child.prototype = (function() {
  var Base = function() {};
  Base.prototype = Parent.prototype;
  return new Base();
}());

これにより、プロトタイプがクラスBaseのプロトタイプに設定された無名関数(と呼ばれる)が作成され、プロトタイプが新しいものに割り当てられます。これにより、継承が保持されますが、プロトタイプチェーンが作成されるときにのコンストラクターは呼び出されません。。ParentChildBaseParent

于 2012-10-24T08:00:56.353 に答える
0

Parent の新しいオブジェクトを作成するときに 1 つのアラートがあり、Child の新しいオブジェクトを作成するときに 1 つのアラートがありますChild.prototype = new Parent;var childObject = new Child(false, false, false);

于 2012-10-24T07:58:25.253 に答える