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?
'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. 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();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.