2

JavaScript で OOP を使用しようとしています。私がしようとしているのは、

と言う2つのクラスがclassAありclassBます。classB で classA を継承しています。お気に入り :

 function classA(){
    this.propA = "somevalue of A";
 }

 function classB(){
    classB.prototype = new classA();              //inheriting
    classB.prototype.constructor = classB;        //updating constructor defination
    this.propB = "somevalue of B";
 }

今、私は classB のオブジェクトを作成しました:

var classBObject = new classB();

そして、次の方法で基本クラスのプロパティ値にアクセスしようとするよりも:

alert(classBObject.propA);      //here i am expecting "somevalue of A"

しかし、アラートは私が空であることを示しています。ここで私が間違っていることを教えてください。

4

1 に答える 1

3

classB のプロトタイプ割り当てをコンストラクタの外に移動します。

function classA(){
    this.propA = "somevalue of A";
 }

 function classB(){
    // classB.prototype.constructor = classB;
    // ^ no need for this, constructor will be overwritten
    //   by classB.prototype = new classA
    this.propB = "somevalue of B";
 }

 classB.prototype = new classA; // assing prototype for classB here
于 2013-02-14T06:50:49.380 に答える