8

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

我可以实现这样的事情:

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

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

4

1 回答 1

11

是的你可以。您必须使用. Object.defineProperty以下是基于现有游戏代码的完整解决方案:

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;
    }
});
于 2015-05-10T10:59:04.983 回答