扩展 Source 原型以拥有一个内存对象
Extend Source prototype to have a memory object
我想存储一些关于我正在收集的能源的信息。理想情况下我会使用 mySource.memory.taken
但 Source 没有内存 属性.
我可以这样实现:
Source.prototype.memory = function() {
return Memory.sources[this.id];
}
但是我可以像其他游戏对象一样实现与 属性 相同的东西而不是方法吗?或者有比这更好的方法吗?
是的,你可以。您必须实施 Getter/Setter interface using 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;
}
});
我想存储一些关于我正在收集的能源的信息。理想情况下我会使用 mySource.memory.taken
但 Source 没有内存 属性.
我可以这样实现:
Source.prototype.memory = function() {
return Memory.sources[this.id];
}
但是我可以像其他游戏对象一样实现与 属性 相同的东西而不是方法吗?或者有比这更好的方法吗?
是的,你可以。您必须实施 Getter/Setter interface using 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;
}
});