gpt4 book ai didi

javascript - ES6 将对象映射到装饰器

转载 作者:行者123 更新时间:2023-12-03 04:13:05 24 4
gpt4 key购买 nike

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

最佳答案

它不起作用,因为 key: {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();

关于javascript - ES6 将对象映射到装饰器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44249948/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com