[英]ES6 Map an object to a decorator
I'd like to map an object with properties (key) to a decorator (value). 我想将具有属性(键)的对象映射到装饰器(值)。 I'd like to use a Weak Map if possible. 如果可能的话,我想使用弱地图。 I have a solution that is working using a string, which is fine except that Weak Maps do not accept strings as keys. 我有一个使用字符串的解决方案,这很好,除了弱映射不接受字符串作为键。 Is this possible with a Map or a WeakMap? 地图或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();
It does not work because different instance of key: {nodeName: 'tag-name-here', component: 'accordion'}
will map to a new memory location each time, so you won't be able to get your desired value this way. 它不起作用,因为键的不同实例: {nodeName: 'tag-name-here', component: 'accordion'}
每次都会映射到新的内存位置,因此您将无法获得所需的值方式。 To make it work, you have to set it to a new variable, so that your code looks like the following: 要使其正常工作,必须将其设置为新变量,以便代码如下所示:
'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();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.