【问题标题】:Extend Source prototype to have a memory object扩展 Source 原型以具有内存对象
【发布时间】:2015-07-20 18:49:48
【问题描述】:

我想存储一些关于我正在收集的能源的信息。理想情况下,我会使用 mySource.memory.taken,但 Source 没有内存属性。

我可以实现这样的:

Source.prototype.memory = function() {
    return Memory.sources[this.id];
}

但是我可以实现与其他游戏对象一样的属性而不是方法吗?还是有比这更好的方法?

【问题讨论】:

    标签: screeps


    【解决方案1】:

    是的,你可以。你必须使用Object.defineProperty 来实现Getter/Setter interface。以下是基于现有游戏代码的完整解决方案:

    Object.defineProperty(Source.prototype, 'memory', {
        get: function() {
            if(_.isUndefined(Memory.sources)) {
                Memory.sources = {};
            }
            if(!_.isObject(Memory.sources)) {
                return undefined;
            }
            return Memory.sources[this.id] = Memory.sources[this.id] || {};
        },
        set: function(value) {
            if(_.isUndefined(Memory.sources)) {
                Memory.sources = {};
            }
            if(!_.isObject(Memory.sources)) {
                throw new Error('Could not set source memory');
            }
            Memory.sources[this.id] = value;
        }
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-09-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多