我正在尝试使用new Function(...)
动态设置原型函数。我尝试了以下(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();
}
}
使用案例:我有一个微服务,将算法存储为资源,然后将其传递到与2种算法作战的模拟器中。
当我尝试此操作时,this.prototype
为undefined
。我可以认为这种情况的唯一原因是因为AI
对象在构造函数执行完之后才完全定义。
我将如何设置原型功能,就像我在这里尝试一样?
更新:
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 :(得分: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();
}
}