首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >动态设置Javascript原型

动态设置Javascript原型
EN

Stack Overflow用户
提问于 2016-06-12 17:05:41
回答 1查看 370关注 0票数 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对象才被完全定义。

我如何设置一个原型功能,就像我在这里试图做的那样?

更新:

代码语言:javascript
复制
this.__proto__.initialize   = new Function(this.algObj.initialize);
this.__proto__.shoot        = new Function(this.algObj.shoot);
this.__proto__.placeShips   = new Function(this.algObj.placeShips);
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2016-06-12 17:26:50

当调用构造函数时,您已经有了要创建的对象的实例,因此您可以简单地修改实例的方法,而无需接触原型:

代码语言: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.initialize   = new Function(this.algObj.initialize);
        this.shoot        = new Function(this.algObj.shoot);
        this.placeShips   = new Function(this.algObj.placeShips);

        this.initialize();
    }
}
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/37776910

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档