如何解决如何在类中存储属性的元信息
我想将元数据与类中的属性相关联,特别是属性名称的缩写。
带有注释:@shortName(缩写),您可以标记每个属性:
function shortName(shortName: string){
return function (target: Object,realName: string){
// Where to store the relation realName <-> shortName ??
}
}
class Record{
@shortName("ts") typeOfStorage: string;
}
class Client extends Record{
@shortName("df") descriptiveField: string;
}
function mapNames(obj: any){ // Return object with shortened names
let ret = {};
for(let prop in obj){
//Here retrieve the short name and add to ret
}
return ret;
}
let client = new Client(); // supposing: { typeOfStorage: "f",descriptiveField: "blah"}
let clientShortened = mapNames(client); // expected: {ts: "f",df: "blah"}
问题是我应该在哪里以及如何存储这些关系,以便可以在派生类的实例中检索它们?
最初,我正在创建一个以target.constructor.name为前缀的全局映射(给出类的名称)。但是在继承的类中,constructor.name是继承的类(因此在示例client
中,我不会跟踪typeOfStorage
(此方法的使用是为了节省存储在每个对象记录的每个属性名称的nonSql DB -firestore-对象中的空间)
解决方法
我可能会在类的原型上存储一张地图。在解析对象的属性时,您可以通过从对象实例开始递归调用Object.getPrototypeOf
来获取原型链。您将必须合并原型链中的所有地图(或仅在每个地图中单独查找属性)。
function shortName(shortName: string)
{
return function (target: Object,realName: string)
{
const t = target as { _propMap?: Map<string,string> };
if (t._propMap == null)
{
// This is probably overkill,because people usually iterate
// properties on the instances,not the prototype.
// Setting enumerable: false hides the property.
Object.defineProperty(t,'_propMap',{
enumerable: false,writable: true,});
t._propMap = new Map<string,string>();
}
t._propMap.set(realName,shortName);
}
}
function getMap(obj: any)
{
// Might want to get the chain first,then iterate in reverse
// so child properties override parent properties
const map = new Map<string,string>();
while (true)
{
obj = Object.getPrototypeOf(obj);
if (obj == Object.prototype)
return map;
if (obj._propMap)
{
let subMap = obj._propMap as Map<string,string>;
subMap.forEach((v,k) => map.set(k,v));
}
}
}
function mapNames(obj: any)
{
const map = getMap(obj);
const ret: any = {};
for (let prop in obj)
{
const name = map.get(prop) ?? prop;
ret[name] = obj[prop];
}
return ret;
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。