我试图使用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);发布于 2016-06-12 17:26:50
当调用构造函数时,您已经有了要创建的对象的实例,因此您可以简单地修改实例的方法,而无需接触原型:
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();
}
}https://stackoverflow.com/questions/37776910
复制相似问题