0

ええと、私はプロトタイプのプログラミング/設計が初めてです。喜んでお手伝いさせていただきます。

問題は、this.__proto__instances「find」メソッド内の「」が「未定義」を返すのはなぜですか?

私のアプローチが間違っている場合は、ご容赦ください。すべての子に対してメソッドを定義することなく、クラス メソッドを呼び出してクラス変数配列内の要素を検索するための正しいアプローチを喜んで知りたいと思います。

問題の詳細は、以下のコードのコメントとして詳述されています。

ありがとうございました。

function Attribute(name,type){
    //some members definition, including uid, name, and type
};

Attribute.prototype.find=function(uid){
    var found_attr=false;
    this.__proto__.instances.forEach(function(attr){ 
        if (attr.uid == uid) found_attr=attr;           
    }); 
    return found_attr;
};

this.__proto__.instances.forEach(function(attr){ 上記は間違った行です。ログには「未定義の forEach メソッドを呼び出せません」と表示されます

function ReferenceAttribute(arg_hash){
    Attribute.call(this,arg_hash.name,arg_hash.type); 
    //some members definition
    this.pushInstance(this); 
};

this.pushInstance(this);このインスタンスを正常に動作する ReferenceAttribute.prototype.instances にプッシュします

ReferenceAttribute.prototype=new Attribute(); 

ReferenceAttribute は、プロトタイプ チェーン メソッドを使用して Attribute を継承します。

ReferenceAttribute.prototype.instances=new Array(); 

上記の行は、参照属性のすべてのインスタンスを含む配列を宣言しています。ReferenceAttribute の新しいオブジェクトごとに、メソッド pushInstance() で実行されて、この配列にプッシュされます。プッシュは常に成功しています。コンソールログで確認しました。配列には ReferenceAtribute インスタンスが含まれています

function ActiveAttribute(arg_hash){
    Attribute.call(this,arg_hash.name,arg_hash.type);
    //some members definition
    this.pushInstance(this); 
};

ActiveAttribute.prototype=new Attribute(); 
ActiveAttribute.prototype.instances=new Array(); 

プログラムで使用する

var ref_attr=ReferenceAttribute.prototype.find("a uid"); 

undefined の forEach メソッドを呼び出せないというエラーが表示されます。メソッドfindを呼び出せるので、うまく継承されます。しかし、find メソッド定義内の「this._proto _instances」は間違っていると思います。

編集 :

Attribute.prototype.pushInstance=function(my_attribute){    
    this.__proto__.instances.push(my_attribute);    
}; 

この機能は動作します。インスタンス配列は、属性自体ではなく、ActiveAttribute または ReferenceAttribute のいずれかによって所有されていますが、この関数はそれを配列にプッシュする際に機能します。

4

2 に答える 2

2

user2736012 があなたの答えを持っているので、コメントしてください:

この__proto__プロパティは、使用中のすべてのブラウザーで標準化またはサポートされているわけではないため、使用しないでください。さらに、オブジェクトの のプロパティにアクセスする場合は、[[Prototype]]標準のプロパティ解決を使用します。

this.instances

継承されたメソッドを直接参照する場合、継承のポイントは何ですか?

于 2013-10-11T03:26:04.093 に答える