0

我想将具有属性(键)的对象映射到装饰器(值)。如果可能,我想使用弱映射。我有一个正在使用字符串的解决方案,除了弱地图不接受字符串作为关键字。这是可能的一个地图或WeakMap?ES6将对象映射到装饰器

'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(); 

回答

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();