gpt4 book ai didi

javascript - 如何使用装饰器向类添加函数

转载 作者:行者123 更新时间:2023-11-28 03:51:39 25 4
gpt4 key购买 nike

我正在尝试创建一个类装饰器,它只是将一个函数(或实际上的属性)添加到一个类中,但没有任何乐趣。

const findDecorator = () => {
return (constructor) => {
constructor.prototype.findMe = () => console.log('You found me!')
}
}

我还尝试使用 target.prototype 模式和其他一些东西,但没有用。有谁有一个简单的例子来说明如何做到这一点?对了,我还扩展了一个类:

@findDecorator()
export default class MyClass extends OtherClass {
shouldFireFirst () {
this.findMe()
}
}

编辑:实际上,问题似乎在于该函数在实例上可用,但在类声明中不可用。

最佳答案

根据评论,假设您将 Babel 与 babel-plugin-transform-decorators-legacy 一起使用,您要做的就是向目标类添加新方法。为此,您需要在装饰器中扩展目标类,如下所示:

const findDecorator = (target) => {
return class extends target {
constructor(...args) {
super();
}

findMe() { console.log('You found me!') }
};
}

@findDecorator
export default class MyClass extends OtherClass {
shouldFireFirst () {
this.findMe()
}
}

new MyClass().shouldFireFirst() // => You found me!

如果您需要将参数传递给装饰器,您也可以这样做:

const findDecorator = (name) => (target) => {
return class extends target {
constructor(...args) {
super();
this.name = name
}

findMe() { console.log(`You found ${this.name}!`) }
};
}

@findDecorator('Waldo')
export default class MyClass extends OtherClass {
shouldFireFirst () {
this.findMe()
}
}

new MyClass().shouldFireFirst() // => You found Waldo!

关于javascript - 如何使用装饰器向类添加函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47949461/

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