繁体   English   中英

ES6将对象映射到装饰器

[英]ES6 Map an object to a decorator

我想将具有属性(键)的对象映射到装饰器(值)。 如果可能的话,我想使用弱地图。 我有一个使用字符串的解决方案,这很好,除了弱映射不接受字符串作为键。 地图或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();

它不起作用,因为键的不同实例: {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(); 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM