我想存储一些我正在收获的能源信息.理想情况下我会使用mySource.memory.taken但Source没有内存属性.
我可以实现这样的事情:
Source.prototype.memory = function() {
return Memory.sources[this.id];
}
Run Code Online (Sandbox Code Playgroud)
但是我可以像其他游戏对象一样实现与属性相同的东西而不是方法吗?还是有比这更好的方法?
art*_*tch 10
是的你可以.您必须使用Getter/Setter接口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;
}
});
Run Code Online (Sandbox Code Playgroud)