gpt4 book ai didi

派生类的 typescript 方法装饰器

转载 作者:搜寻专家 更新时间:2023-10-30 21:59:22 25 4
gpt4 key购买 nike

我对 'h.collection' 的期望是 [['a', alpha], ['b', beta]],'w.collection' 是 [['a', alpha], ['c', gama]].

但是 Greeter、Hello 和 World 只是共享同一个“集合”,对吧?

那么,我应该更改哪些代码?

function alias(alias: string) {
return function (target: any, propertyKey: string, descriptor: PropertyDescriptor) {
let func = target[propertyKey];
func.alias = alias;
if (!target.collection) {
target.collection = new Map();
}
target.collection.set(alias, func);
};
}

abstract class Greeter {
public collection: Map<string, Function>;
@alias('a')
alpha(){}
}

class Hello extends Greeter {
@alias('b')
beta(){}
}

class World extends Greeter {
@alias('c')
gama(){}
}

let h = new Hello();
let w = new World();

console.log(h.collection);
console.log(w.collection);

最佳答案

这是我的笨拙解决方案。这是我能做的最优雅的方式。

function alias(alias: string) {
return function (target: any, propertyKey: string, descriptor: PropertyDescriptor) {
let className: string = target.constructor.name;
let func = descriptor.value;
func.alias = alias;

target.shadowCollections = target.shadowCollections || {}
let shadowCollections = target.shadowCollections;

shadowCollections[className] = shadowCollections[className] || new Map();
let collection: Map<string, Function> = shadowCollections[className];

collection.set(alias, func);
};
}

function fix<T extends { new(...args: any[]): {} }>(ctor: T) {
let all: [string, Function][] = [];
function* getClassNames(_ctor: T) {
while (_ctor && _ctor.name) {
yield _ctor.name;
_ctor = Object.getPrototypeOf(_ctor);
}
}
for (let className of getClassNames(ctor)) {
let current: Map<string, Function> = ctor.prototype.shadowCollections[className];
all.push(...current);
}
all.sort(([a,], [b,]) => a < b ? -1 : (a > b ? 1 : 0));
delete ctor.prototype.shadowCollections;
return class extends ctor {
_collection = new Map(all);
}
}

abstract class Greeter {
protected _collection: Map<string, Function>;
public get collection(): Map<string, Function> {
return this._collection;
}
@alias('a')
alpha() { }
}

@fix
class Hello extends Greeter {
@alias('b')
beta() { }
}

@fix
class World extends Greeter {
@alias('c')
gama() { }
}

let h = new Hello();
let w = new World();

console.log(h.collection);
console.log(w.collection);

关于派生类的 typescript 方法装饰器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47195626/

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