5

スーパークラス A から継承するサブクラス B を作成したいと思います。私のコードは次のとおりです。

function A(){
    this.x = 1;
}

B.prototype = new A;
function B(){
    A.call(this);
    this.y = 2;
}
b = new B;
Console.log(b.x + " " + b.y );

実行すると、B is undefined と表示されます。

4

4 に答える 4

17

プロトタイプにアクセスする前に、B コンストラクター関数を定義する必要があります。

function A(){
  this.x = 1;
}

function B(){
  A.call(this);
  this.y = 2;
}

B.prototype = new A;

b = new B;
console.log(b.x + " " + b.y );  // outputs "1 2"
于 2009-07-30T03:54:59.957 に答える
7
B.prototype = new A;
function B(){
    A.call(this);
    this.y = 2;
}

する必要があります

function B(){
    A.call(this);
    this.y = 2;
}
B.prototype = new A;
于 2009-07-30T03:51:12.787 に答える
5

Lynda.com は、次のように、次にコンストラクターを B に再割り当てすることをお勧めします。

function B() {
   A.call(this);
   this.y = 2;
}

B.prototype = new A;
B.prototype.constructor = B;
于 2011-04-15T22:48:48.573 に答える