簡體   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