1

I am trying to set a prototype function dynamically using new Function(...). I have tried the following (es6):

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();
    }
}

USE CASE: I have a micro service that stores algorithms as the resource which will then be passed into a simulator that battles 2 algorithms.

when I try this, this.prototype is undefined. The only reason I can think this might be the case is because the AI object is not fully defined until after the constructor is done executing.

How would I go about setting a prototype function like I am trying to do here?

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);
frankgreco
  • 1,426
  • 1
  • 18
  • 31

1 Answers1

3

When the constructor is invoked you already have an instance of the object you're creating, and thus you can simply modify the instance's methods without touching the prototype:

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();
    }
}
Schlaus
  • 18,144
  • 10
  • 36
  • 64