我想将具有属性(键)的对象映射到装饰器(值)。如果可能的话,我想使用弱地图。我有一个使用字符串的解决方案,除了Weak Maps不接受字符串作为键之外,这很好。这可能是Map或WeakMap吗?
'use strict';
class Accordion {
constructor() {}
}
let Decorators = new Map();
Decorators.set({nodeName: 'tag-name-here', component: 'accordion'}, (client) => { return new Accordion(client) });
class Client {
constructor() {
let key = {nodeName: 'tag-name-here', component: 'accordion'}
let decorator;
if (Decorators.has(key)) {
decorator = Decorators.get(key)(this);
}
console.log(decorator); //undefined, unless I use a string as a key.
}
}
new Client();
答案 0 :(得分:1)
它不起作用,因为密钥的不同实例:{nodeName: 'tag-name-here', component: 'accordion'}
每次都会映射到新的内存位置,因此您无法以这种方式获得所需的值。要使其工作,您必须将其设置为新变量,以便您的代码如下所示:
'use strict';
class Accordion {
constructor() {}
}
let Decorators = new Map();
const key = {nodeName: 'tag-name-here', component: 'accordion'};
Decorators.set(key, (client) => { return new Accordion(client) });
class Client {
constructor() {
let decorator;
if (Decorators.has(key)) {
decorator = Decorators.get(key)(this);
}
console.log(decorator); // this should return an object
}
}
new Client();