2016-06-12 29 views
1

new Function(...)を使用してプロトタイプ関数を動的に設定しようとしています。私は、次の(ES6)を試みた:Javascriptプロトタイプを動的に設定する

export default class AI { 

    constructor(algObj, player) { 
     this.player = player; 
     this.algObj = algObj; 

     //create the shoot and placeShips prototypes form the this.algObj property 
     this.prototype.initialize = new Function(this.algObj.initialize); 
     this.prototype.shoot  = new Function(this.algObj.shoot); 
     this.prototype.placeShips = new Function(this.algObj.placeShips); 

     this.initialize(); 
    } 
} 

使用例:私は、2つのアルゴリズムを戦いシミュレータに渡されるリソースようなアルゴリズムを格納するマイクロサービスを有しています。

これを試してみるとthis.prototypeundefinedです。コンストラクタの実行が完了するまで、AIオブジェクトが完全に定義されていないため、これが当てはまると思う唯一の理由があります。

ここでやろうとしているように、プロトタイプ関数を設定するにはどうすればよいですか?

UPDATE:コンストラクタが呼び出されると

this.__proto__.initialize = new Function(this.algObj.initialize); 
this.__proto__.shoot  = new Function(this.algObj.shoot); 
this.__proto__.placeShips = new Function(this.algObj.placeShips); 
+0

AIを1つのオブジェクトインスタンスにのみ使用する予定ですか? – trincot

+0

私は自分の編集と更新にユースケースを追加しました。 – frankgreco

+0

ゲームごとに1つのAIインスタンスがあり、シミュレーションごとに複数のゲームが存在します。 – frankgreco

答えて

3

あなたはすでにあなたが作成しているオブジェクトのインスタンスを持っているので、あなたは、単にプロトタイプを触れることなく、インスタンスのメソッドを変更することができます。

export default class AI { 

    constructor(algObj, player) { 
     this.player = player; 
     this.algObj = algObj; 

     //create the shoot and placeShips prototypes form the this.algObj property 
     this.initialize = new Function(this.algObj.initialize); 
     this.shoot  = new Function(this.algObj.shoot); 
     this.placeShips = new Function(this.algObj.placeShips); 

     this.initialize(); 
    } 
} 
+0

これは機能します!したがって、3つの関数がAI.prototype – frankgreco

+1

@Frankに追加されます。いいえ、それらはコンストラクタのインスタンスに追加されます。プロトタイプはそのままです。 – Schlaus

+0

@ jfriend00:明らかに 'algObj'にはコード文字列が含まれています。そうでなければ動作しません。それがなぜそれを行うのか、それが良い考えであるかどうか、他のところで議論するほうがいいです。 – Bergi

関連する問題